Hab*_*bax 2 ruby lambda activerecord ruby-on-rails ruby-on-rails-3
我的模特在这里:
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
Run Code Online (Sandbox Code Playgroud)
我想topics
用current_user
相关的for 来获取所有内容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
Run Code Online (Sandbox Code Playgroud)
这很难看并且做了太多的数据库查询.我想要这样的东西:
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
Run Code Online (Sandbox Code Playgroud)
这可能吗?我还有其他选择吗?
谢谢!
*嗯我不确定我理解你的问题,但这可能会对你有所帮助:
# 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
Run Code Online (Sandbox Code Playgroud)
如您所见,范围的参数for_user
可以是User对象或用户ID.
希望这可以帮助!
类似的问题:
归档时间: |
|
查看次数: |
5115 次 |
最近记录: |