轨3,HAS_ONE /的has_many与拉姆达条件(Rails 3, has_one / has

2019-06-21 06:23发布

在这里我的模型:

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

这可能吗? 我有没有任何替代?

谢谢!

Answer 1:

*嗯,我不知道我理解你的问题,但是这可能会帮助你:

# 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 可以是用户对象或用户ID。

希望这可以帮助!

类似的问题:

  • 如何查询基于另一个模型的属性模型属于第一种模式?
  • 导轨和“存在”的活动记录查询关联
  • 轨道4范围,找到父母无子女
  • 加入与活动记录多个表


文章来源: Rails 3, has_one / has_many with lambda condition