在这里我的模型:
class User < ActiveRecord::Base
has_many :bookmarks
end
class Topic < ActiveRecord::Base
has_many :bookmarks
end
class Bookmark < ActiveRecord::Base
belongs_to :user
belongs_to :topic
attr_accessible :position
validates_uniqueness_of :user_id, :scope => :topic_id
end
我想获取所有topics
与为current_user
,相关的bookmark
。 ATM,我做的:
Topic.all.each do |t|
bookmark = t.bookmarks.where(user_id: current_user.id).last
puts bookmark.position if bookmark
puts t.name
end
这是丑陋的和做过多的数据库查询。 我想是这样的:
class Topic < ActiveRecord::Base
has_one :bookmark, :conditions => lambda {|u| "bookmarks.user_id = #{u.id}"}
end
Topic.includes(:bookmark, current_user).all.each do |t| # this must also includes topics without bookmark
puts t.bookmark.position if t.bookmark
puts t.name
end
这可能吗? 我有没有任何替代?
谢谢!