Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In this case, I would lean against making a separate <code>Spend</code> model, since all it does is calculate data that is already present in the database. Unless you have severe caching requirements (and I doubt it in your case), you can use simple instance methods to retrieve the data you want.</p> <p>First figure out how your Usage and Price models are related. Since you seem to be associating them by id, it appears to be a one-to-one relationship (correct me if I'm wrong on this). However, associating by assuming they have the same primary key is a dangerous approach - rather have one model point to the other using a foreign key. We'll pick the <code>Price</code> model to hold a primary key for <code>Usage</code>, but the reverse can also work. You'll need to add a column using a migration like this:</p> <pre><code>def change add_column :prices, :usage_id, :integer end </code></pre> <p>Your models should then look like this:</p> <pre><code>class Usage &lt; ActiveRecord::Base has_one :price def spend usage * price.price end end class Price &lt; ActiveRecord::Base belongs_to :usage end </code></pre> <p>And you can find your <code>spend</code> value for an individual <code>usage</code> item like this:</p> <pre><code>usage = Usage.find(some_id) puts usage.spend </code></pre> <p>Or you can get multiple 'spends' like this:</p> <pre><code>Usage.include(:price).each do |usage| puts usage.spend end </code></pre> <p>I've left out any reference to month, as I'm not sure how you are using it or if it's needed at all for calculating <code>spend</code>.</p>
 

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