I have messages that users send to other users. There are two models: post and: user, and: post has the following associations:
belongs_to :from_user, :class_name => "User", :foreign_key => "from_user_id" belongs_to :to_user, :class_name => "User", :foreign_key => "to_user_id"
Both: user and: post have an "is_public" column indicating that either one message or the entire user profile can be public or private.
My goal is to get a list of messages that are public and whose recipients have public profiles. At the same time, I would like to โincludeโ the information of both the sender and the recipient in order to minimize the number of db calls. The problem is that I effectively "include" the same table twice through the named associations, but in my "conditions" I need to make sure that I only filter the recipient's is_public column.
I cannot do the following because the โconditionsโ do not accept the association name as a parameter:
Post.find(:all, :include => [ :to_user, :from_user ], :conditions => { :is_public => true, :to_user => { :is_public => true }})
So, one of the ways I can do this is to make an extra "join" in the "users" table:
Post.find(:all, :include => [ :to_user, :from_user ], :joins => "inner join users toalias on posts.to_user_id = toalias.id", :conditions => { :is_public => true, 'toalias.is_public' => true })
Is there a better, possibly cleaner way to do this?
Thanks in advance
ruby-on-rails activerecord
avioing
source share