Rails 3, has_one / has_many z warunkiem lambda
Oto moje modele:
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
Chcę pobrać wszystkotopics
z, dlacurrent_user
, Powiązanebookmark
. ATM, ja:
Topic.all.each do |t|
bookmark = t.bookmarks.where(user_id: current_user.id).last
puts bookmark.position if bookmark
puts t.name
end
To jest brzydkie i wykonuj zbyt wiele zapytań DB. Chciałbym coś takiego:
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
czy to możliwe? Czy mam jakąś alternatywę?
Dziękuję Ci!