我有以下课程:
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关联,仅包含这些注释 已被批准。
答案 0 :(得分:0)
找到它,忘了在选择中选择外键car_id
。