activerecord - rails find: using conditions while including same table twice via different named associations -


i have posts sent users other users. there 2 models - :post , :user, , :post has following named 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 , :post have "is_public" column, indicating either single post and/or entire user profile can public or private.

my goal fetch list of posts public , recipients have public profiles. @ same time, "include" both sender , recipient info minimize # of db calls. challenge "including" same table twice via named associations, in "conditions" need make sure filter recipient's "is_public" column.

i can't following because "conditions" not accept association name parameter:

post.find(:all, :include => [ :to_user, :from_user ],    :conditions => { :is_public => true, :to_user => { :is_public => true }}) 

so, 1 way can accomplish doing additional "join" on "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 better, perhaps cleaner, way this?

thanks in advance

i facing same problem , found solution after watching sql query generated rails query, sql query automatically generates alias try this,

post.find(:all, :include => [ :to_user, :from_user ],         :conditions => { :is_public => true, 'to_users_posts.is_public' => true }) 

it worked me :)


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -