I have an Order class, and a Pack class, both using ActiveRecord. The Order contains Packs. In my validation of Order, I am testing for the existence of a relationship to one or more Packs. 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. 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?
Try using
.lengthinstead of.count.When you use
countyou’re actually performing a database query. And because you’re doing it on validation, before anything has been saved to the database, you’re always getting zero.lengthon the other hand works on the object level and doesn’t hit the database at all. So it should work for you.