使用ruby on rails验证具有多态关联的模型上的时间重叠



我正试图在模型中创建一个验证(我认为实际上最好在数据库级别进行验证(,这样用户就不能在2天内购买已经购买的物品(2天后,如果他/她再次购买也没关系(。

我有一个"购买"行为的模型,每个购买行为都有一个名为"可购买"的相关项目。此外,每个购买操作都有一个相关联的user_id。

我在购买模型中尝试这样做(但我的问题是,我不知道如何正确编写此验证,甚至不知道在编写验证方法时如何检索"purchasable.id"或"user.id"(

class Purchase < ApplicationRecord
belongs_to :purchasable, polymorphic: true
belongs_to :user
validates :price, presence: true
validate :no_purchase_overlap
def no_purchase_overlap
allPur = Purchase.includes(:purchasable).all
if allPur.where("created_at >= ? AND user_id = ? AND purchase_id = ?", (Time.now-2.days), user_id, purchasable.id)
errors.add(:date_end, 'it overlaps another purchase')
end
end
end

购买及其可购买性看起来像:

irb(main):006:0> Purchase.first
Purchase Load (0.1ms)  SELECT "purchases".* FROM "purchases" ORDER BY "purchases"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<Purchase id: 1, price: 0.299e1, quality: "SD", purchasable_type: "Season", purchasable_id: 9, user_id: 1, created_at: "2020-02-25 09:34:59", updated_at: "2020-02-25 09:34:59">
irb(main):007:0> Purchase.first.purchasable
Purchase Load (0.1ms)  SELECT "purchases".* FROM "purchases" ORDER BY "purchases"."id" ASC LIMIT ?  [["LIMIT", 1]]
Season Load (0.2ms)  SELECT "seasons".* FROM "seasons" WHERE "seasons"."id" = ? LIMIT ?  [["id", 9], ["LIMIT", 1]]
=> #<Season id: 9, title: "Brandy of the Damned", plot: "Here's looking at you, kid.", number: 1, created_at: "2020-02-25 09:34:17", updated_at: "2020-02-25 09:34:17">

现在它没有通过我的测试,似乎不允许保存任何购买:

it 'a movie can not be purchased by the same user more than once' do
purchase = Purchase.new(price: 2.99, quality: 'HD', purchasable: movie, user: user)
purchase_rep = Purchase.new(created_at: Time.now + 1.day ,price: 1.99, quality: 'SD', purchasable: movie, user: user)
expect { purchase.save }.to change { user.purchases.count }.by(1)
expect { purchase_rep.save }.to raise_error
end

故障消息:

故障:

1) Purchase When creating a purchase a movie can not be purchased by the same user more than once
Failure/Error: expect { purchase.save }.to change { user.purchases.count }.by(1)
expected `user.purchases.count` to have changed by 1, but was changed by 0
# ./spec/models/purchase_spec.rb:14:in `block (3 levels) in <main>'

使用解决

def no_purchase_overlap
if Purchase.where("created_at >= ? AND user_id = ?", (Time.now-2.days), self.user.id).any?{|purchase| purchase.purchasable == self.purchasable}
errors.add(:date_end, 'it overlaps another purchase')
end
end

相关内容

  • 没有找到相关文章