http://guides.rubyonrails.org/v4.1/active_record_querying.html#eager-loading-multiple-associations
我的 model 之间的关联是这样的
class Video < ActiveRecord::Base
belongs_to :category
has_many :reviews, -> { order(created_at: :desc) }
has_many :queue_items
end
class QueueItem < ActiveRecord::Base
belongs_to :video
belongs_to :user
end
class Category < ActiveRecord::Base
has_many :videos, -> { order(created_at: :desc) }
end
为什么在有 category 参与的情况下的查询都会返回一个 Class:#<QueueItem::ActiveRecord_Relation,
这个不能拿来用啊,@queue_items[0]
会报错NoMethodError: undefined method 'each' for nil:NilClass
。只 includes reviews 就没问题。请看:
4: def index
5: @queue_items = QueueItem.includes(video: ['reviews', 'category'])
=> 6: binding.pry
7: end
[1] pry(#<QueueItemsController>)> @queue_items
QueueItem Load (0.3ms) SELECT "queue_items".* FROM "queue_items"
Video Load (0.2ms) SELECT "videos".* FROM "videos" WHERE "videos"."id" IN (8, 9, 1)
Review Load (0.3ms) SELECT "reviews".* FROM "reviews" WHERE "reviews"."video_id" IN (1, 8, 9) ORDER BY "reviews"."created_at" DESC
Category Load (0.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" IN (2, 1)
=> #<#<Class:#<QueueItem::ActiveRecord_Relation:0x007fce43081600>>:0x3fe721840b00>
#只load reviews的话就没问题
[2] pry(#<QueueItemsController>)> @queue_items = QueueItem.includes(video: ['reviews'])
CACHE (0.0ms) SELECT "queue_items".* FROM "queue_items"
CACHE (0.0ms) SELECT "videos".* FROM "videos" WHERE "videos"."id" IN (8, 9, 1)
CACHE (0.0ms) SELECT "reviews".* FROM "reviews" WHERE "reviews"."video_id" IN (1, 8, 9) ORDER BY "reviews"."created_at" DESC
=> [#<QueueItem id: 1, position: 2, user_id: 1, video_id: 8>,
#<QueueItem id: 2, position: 1, user_id: 1, video_id: 9>,
#<QueueItem id: 3, position: 1, user_id: 2, video_id: 8>,
#<QueueItem id: 5, position: 3, user_id: 1, video_id: 1>]
[3] pry(#<QueueItemsController>)> @queue_items = QueueItem.includes(video: ['category'])
CACHE (0.0ms) SELECT "queue_items".* FROM "queue_items"
CACHE (0.0ms) SELECT "videos".* FROM "videos" WHERE "videos"."id" IN (8, 9, 1)
CACHE (0.0ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" IN (2, 1)
=> #<#<Class:#<QueueItem::ActiveRecord_Relation:0x007fce3f5c5480>>:0x3fe71fae2a40>
[4] pry(#<QueueItemsController>)> @queue_items[0]
CACHE (0.0ms) SELECT "queue_items".* FROM "queue_items"
CACHE (0.0ms) SELECT "videos".* FROM "videos" WHERE "videos"."id" IN (8, 9, 1)
CACHE (0.0ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" IN (2, 1)
NoMethodError: undefined method `each' for nil:NilClass
from /Users/wangxuefei/.rvm/gems/ruby-2.1.2@myflix/gems/activerecord-4.1.1/lib/active_record/associations/preloader/association.rb:87:in `block in associated_records_by_owner'
到底是哪里出错了呢?
劳烦各位啦