我有以下课程:
class Car < ActiveRecord::Base
has_many :adverts, :dependent => :destroy
has_many :active_adverts, :class_name => 'Advert', :select => "adverts.id, adverts.availability_state, adverts.source_name, adverts.last_observed_at", :conditions => "availability_state = 'active'"
end
当我这样做时:cars = Car.where(:brand => 'BMW').includes(:adverts)
它工作正常,并返回我请求的汽车数组,并且广告渴望正确加载。
如果我这样做:cars = Car.where(:brand => 'BMW').includes(:active_adverts)
它似乎执行了预期的查询,但它返回了一个ActiveRecord::Relation
对象,如果我问cars.first
我得到:
NoMethodError: undefined method `each' for nil:NilClass
from /Users/nk/.rvm/gems/ruby-1.9.3-p194@au/gems/activerecord-3.2.13/lib/active_record/associations/preloader/association.rb:88:in `block in associated_records_by_owner'
我究竟做错了什么?
PS。我听从了她的建议:http: //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
它在哪里声明:
如果您确实希望只加载关联的某些成员,通常更自然地包含一个定义了条件的关联:
class Post < ActiveRecord::Base has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true] end
Post.includes(:approved_comments) 这将加载帖子并急切加载approved_comments 关联,该关联仅包含已批准的评论。