Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails: filter associations based on several relations and conditions
    primarykey
    data
    text
    <p>In my application I the have the models Category, Item, Property and PropertyValuation. The idea is that a category contains items, and an item has several properties. PropertyValuation purpose is to store the property value for the specific items. The models are defined as above:</p> <pre><code>class Category &lt; ActiveRecord::Base attr_accessible :name, :description, :parent, :children, :items, :parent_id has_many :children, :class_name =&gt; "Category", :foreign_key =&gt; "parent_id", :dependent =&gt; :nullify belongs_to :parent, :class_name =&gt; "Category" has_many :categorizations has_many :items, :through =&gt; :categorizations end class Item &lt; ActiveRecord::Base attr_accessible :name, :description, :property_valuations, :barcode has_many :property_valuations, :dependent =&gt; :destroy has_many :properties, :through =&gt; :property_valuations has_many :categorizations has_many :categories, :through =&gt; :categorizations end class Property &lt; ActiveRecord::Base attr_accessible :name, :description, :value_type, :unit, :unit_id has_many :property_valuations, :dependent =&gt; :destroy has_many :items, :through =&gt; :property_valuations has_many :property_ranges, :dependent =&gt; :destroy belongs_to :unit end class PropertyValuation &lt; ActiveRecord::Base attr_accessible :property, :item, :value, :categorization belongs_to :property belongs_to :item end </code></pre> <p>Now my question, I've successfully managed to filter categories items by name by doing this:</p> <pre><code>@category.items.where("lower(items.name) like ?", "%#{params[:keywords].downcase}%") </code></pre> <p>But now I also want to filter those items depending on the associated property value. I receive the property ids and the values for each property (exact value, minimum value or maximum value), and the idea is to build the query dynamically. Given my models, how can I do this for example: I want the items whose name contains "foo", and where property with id=1 has value 2, property with id=2 has value&lt;10, and property with id=8 has value>2 and value&lt;5.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload