[英]ActiveRecord relationship validation with error trying to use 'count'
I have an Order class, and a Pack class, both using ActiveRecord. 我有一个Order类和一个Pack类,它们都使用ActiveRecord。 The Order contains Packs.
订单包含包装。 In my validation of Order, I am testing for the existence of a relationship to one or more Packs.
在验证订单时,我正在测试是否存在与一个或多个Pack的关系。 See the following code:
请参见以下代码:
class Order < ActiveRecord::Base
belongs_to :user
has_many :order_packs
has_many :packs, :through => :order_packs
validate :my_custom_validation
def my_custom_validation
errors.add(:packs, "Your order was empty.") if packs.count < 1
end
end
Seems simple enough, but it doesn't work; 看起来很简单,但是却行不通。
packs.count
is always zero. packs.count
始终为零。 So I changed the validation to this code: 所以我将验证更改为以下代码:
def my_custom_validation
errors.add(:packs, "packs is: #{packs}")
errors.add(:packs, "packs.count is: #{packs.count}")
errors.add(:packs, "packs.any? is: #{packs.any?}")
end
just to see what the deal was, and got this interesting output: 只是看看这是什么交易,并得到以下有趣的输出:
Can anyone tell me why count
is zero? 谁能告诉我为什么
count
为零?
Try using .length
instead of .count
. 尝试使用
.length
而不是.count
。
When you use count
you're actually performing a database query. 使用
count
,实际上是在执行数据库查询。 And because you're doing it on validation, before anything has been saved to the database, you're always getting zero. 而且由于您是在验证时进行的,因此在将任何内容保存到数据库之前,总是会得到零。
length
on the other hand works on the object level and doesn't hit the database at all. 另一方面,
length
在对象级别起作用,根本不会影响数据库。 So it should work for you. 因此它应该为您工作。
length and size, both are same, and count performs SQL COUNT query, 长度和大小都相同,并且count执行SQL COUNT查询,
You should read count vs length vs size 您应该阅读计数vs长度vs尺寸
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.