本文介绍了Rails 3,具有 lambda 条件的 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
我想获取所有topics
,对于current_user
,关联的bookmark
.ATM,我愿意:
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 { |user| includes(:bookmarks).where(bookmarks: { user_id: user.try(:id) || user} ) }
# call
Topic.for_user(current_user) # => Array of Topics
如您所见,for_user
范围的参数 可以是用户对象或用户 ID.
As you can see the parameter of the scope for_user
can be a User object OR a user id.
希望这有帮助!
类似问题:
这篇关于Rails 3,具有 lambda 条件的 has_one/has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!