2

这是我的模型:

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

我想topicscurrent_user关联的bookmark. 提款机,我做:

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

这可能吗?我有其他选择吗?

谢谢!

4

1 回答 1

6

*嗯,我不确定我是否理解您的问题,但这可能会对您有所帮助:

# code
class Topic < ActiveRecord::Base
  scope :for_user, lambda { |user| includes(:bookmarks).where(bookmarks: { user_id: user.try(:id) || user} ) }

# call
Topic.for_user(current_user) # => Array of Topics

如您所见,范围的参数for_user 可以是 User 对象或用户 id

希望这可以帮助!

类似的问题:

于 2012-11-22T15:54:38.520 回答