Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your models would start off looking something like this:</p> <pre><code>class Price &lt; ActiveRecord::Base belongs_to :item belongs_to :category belongs_to :discount scope :category, where("prices.category_id IS NOT NULL") scope :discount, where("prices.discount_id IS NOT NULL") end class Item &lt; ActiveRecord::Base has_many :prices end class Category &lt; ActiveRecord::Base has_many :prices end class Discount &lt; ActiveRecord::Base has_many :prices end </code></pre> <p>One way of doing this is to add a class method to <code>Price</code> that encapsulates this logic:</p> <pre><code>class Price &lt; ActiveRecord::Base def self.used discount_items_sql = self.discount.select("prices.item_id").to_sql where("prices.discount_id IS NOT NULL OR prices.item_id NOT IN (#{discount_items_sql})") end end </code></pre> <p>This is effectively the same as this query:</p> <pre><code>SELECT * FROM prices WHERE prices.discount_id IS NOT NULL -- the discount_id is present on this record, OR prices.item_id NOT IN ( -- or no discount_id is present for this item SELECT item_id FROM prices WHERE discount_id IS NOT NULL) </code></pre> <p>You can add these helper methods on your <code>Item</code> model for simplicity:</p> <pre><code>class Item &lt; ActiveRecord::Base def category_price prices.category.first end def discount_price prices.discount.first end def used_price prices.used.first end end </code></pre> <p>Now you can easily get each individual 'type' of price for a single item (will be <code>nil</code> for prices that aren't available):</p> <pre><code>item.category_price item.discount_price item.used_price </code></pre>
 

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