轨道3,HAS_ONE /的has_many与拉姆达条件 [英] Rails 3, has_one / has_many with lambda condition

查看:263
本文介绍了轨道3,HAS_ONE /的has_many与拉姆达条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我的模型:

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

我想获取所有主题用,为 CURRENT_USER ,相关的书签。自动取款机,我做的:

I want to fetch all topics with, for current_user, the associated bookmark. ATM, I do:

Topic.all.each do |t|
    bookmark = t.bookmarks.where(user_id: current_user.id).last
    puts bookmark.position if bookmark
    puts t.name
end

这是丑陋的,做了太多的数据库查询。我想是这样的:

This is ugly and do too much DB queries. I would like something like this:

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

这可能吗?我有没有任何别的选择吗?

Is this possible? Have I any alternative?

感谢您!

推荐答案

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

*Hmm I'm not sure I understood your question but this may help you:

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

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

正如你所看到的参数范围 for_user 可以是用户对象或用户ID

希望这有助于!

类似的问题:

  • <一个href="http://stackoverflow.com/questions/23633301/how-to-query-a-model-based-on-attribute-of-another-model-which-belongs-to-the-fi/23633352#23633352">How查询一个模式的基础上,属于所述第一模型的另一模型的属性?中
  • <一个href="http://stackoverflow.com/questions/18234602/rails-active-record-querying-association-with-exists/18234998#18234998">Rails与活动记录查询协会'存在'
  • <一个href="http://stackoverflow.com/questions/18082096/rails-4-scope-to-find-parents-with-no-children/18082147#18082147">Rails 4范围找父母没有子女
  • <一个href="http://stackoverflow.com/questions/24266069/join-multiple-tables-with-active-records/24266583#24266583">Join与活跃记录多个表
  • How to query a model based on attribute of another model which belongs to the first model?
  • Rails active record querying association with 'exists'
  • Rails 4 scope to find parents with no children
  • Join multiple tables with active records

这篇关于轨道3,HAS_ONE /的has_many与拉姆达条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆