views:

24

answers:

1

How do I write a find(:all) query in rails (v2.3.5) that has parameters both in the model I am running the 'find' on, and in another table? e.g. I am trying to search for 'posts' by 'author' and 'tag'. Author is an attribute of post, whereas tag is associated with it through another table. I can get the tags by including ':joins => :tags', and adding conditions but then I can't figure out how to add in conditions to specify a given user.

Also any suggestions on a good reference for rails query syntax would be great. I can't seem to figure out enough from the v2.3 Rails Guide on queries. Thanks!

+1  A: 

Is this what you are looking for:

Post.all(:include => :tags, 
         :conditions => ["posts.author_id=? AND tags.name IN (?)",
                            author_id, ['tag1','tag2']])

I am assuming you are going need to see the tags that is why I used the include instead of join. It prevents future SQL calls to load the tags. If you are doing this frequently then you are going to want to look at named_scope (or scope in Rails 3).

Peer

Peer Allan
lovely. although it didn't recognize 'posts.author_id', 'author_id' alone worked just fine.
Phil_Ken_Sebben