Rails 3, has_one / has_many with lambda condition
activerecord, lambda, ruby, ruby-on-rails, ruby-on-rails-3
Solution
*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
As you can see the parameter of the scope `for_user` can be a User object OR a user id.
Hope this helps!
Similar questions:
- 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
Problem
Here my models: ``` 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 ``` 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? Thank you!