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
Post a Comment