Rails 3, has_one / has_many with lambda condition

ghz 1years ago ⋅ 7238 views

Question

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!


Answer

*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: