has_and_belongs_to_many() with attributes

Damaris Fuentes wrote: > Hi you all, > I have a "has_and_belongs_to_many()" declaration between models "Pages" > and "Properties". However, this relation has another attribute, called > "value".

> I want to search the pages that have a specific property, but with an > specific value. > To find the pages with the specific property, I have the following > method in the controller: > def show_appears > property = Property.find_by_name(@params[:name]) > @pages_with_property = property.pages > end > But, how can I get from "@pages_with_property" the pages with the exact > value from "@params[:value]"? I can do it stating the SQL statement as > it is, but I suppose Rails may have a smarter way to do it :frowning:

> Thanks.try: def show_appears   property = Property.find_by_name(@params[:name])   @pages_with_property = property.pages.find(:all, :conditions => "value = #{params[:value]}") end

That isnt the most secure way, but it should give you the Pages with properties of params[:name] and value of params[:value]

Indeed, vulnerable to SQL injection. Use the interpolated form of the conditions options:

property.pages.find(:all, :conditions => ["value = ?", params[:value] ] )

(Otherwise the right answer though :slight_smile: