activerecord - rails 3, how to do this easy query across two tables? -


i think trivial query eludes me...

person has_many items item has_many keywords 

item has fields id, person_id, name

keyword has fields id, item_id, txt

in person controller:

def find_all_items_matching_keyword(aword)    ???? end 

is there single query returns items (item.person_id = self.id) , associated (keyword.txt = aword)

this query simple enough should build single scope this:

class item   scope :by_keyword, lambda{ |keyword| joins(:keywords).where('keywords.txt = ?', keyword) } end 

you can query items, in controller, particular person this:

class personscontroller   def action     @person = person.find(params[:id])     @items_by_keyword = @person.items.by_keyword(params[:aword])   end end 

you can loop on list in view, example:

<% @items.by_keyword.each |item| %>   <%= item.name %> <% end %> 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -