title: Populating Rails Fields Based on Calculation
body: <p>In my Rails 3.2 app, I want to populate some fields based on calculations where the field values users enter are the variables.  However, with my current code, the calculation seems to only work based on the values already in the database - it doesn't calculate correctly on the initial save, but it will calculate correctly if I go back in the record and save it a second time.</p>
  
  <p>I have these four fields in my model (Trade):</p>
  
  <ol>
  <li>entry_price</li>
  <li>exit_price</li>
  <li>percent_result</li>
  <li>dollar_result</li>
  </ol>
  
  <p>The user creates a trade with an entry price, and then later edits the trade with the exit_price.  When the exit_price is entered, the app should calculate percent_result and dollar_result.  However, right now, these result fields are not populating correctly on the first update - it seems to be because it doesn't read the exit_price from the field (when a user enters it in the form), only once it is saved in the DB.</p>
  
  <p>What is going wrong in my controller?</p>
  
  <p>my controller:</p>
  
  <pre><code>def update
    @trade = Trade.find(params[:id])
    exit_price = params[:trade][:exit_price]
  
    if !exit_price.blank?
      @trade.percent_result = ((exit_price.to_f - @trade.entry_price)/@trade.entry_price) * 100
      @trade.dollar_result = exit_price.to_f - @trade.entry_price 
    end
  
    params[:trade][:exit_date] = Date.strptime(params[:trade][:exit_date], '%m/%d/%Y') unless params[:trade][:exit_date].blank?
    params[:trade][:entry_date] = Date.strptime(params[:trade][:entry_date], '%m/%d/%Y') unless params[:trade][:entry_date].blank?
    respond_to do |format|
      if @trade.update_attributes(params[:trade])
        format.html { redirect_to @trade, :flash =&gt; {:share =&gt;"Your trade was successfully updated.  Don't forget to share it with your friends, so you can profit together!"} }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @trade.errors, status: :unprocessable_entity }
      end
    end
  end
  </code></pre>
  
  <p>the view</p>
  
  <pre><code>&lt;%= simple_form_for(@trade, :html=&gt;{:class=&gt; "form-horizontal well"})  do |f| %&gt;  
    &lt;%= f.text_field :entry_price, :class=&gt;"input-small" %&gt;
    &lt;%= f.text_field :exit_price, :class=&gt;"input-small" %&gt;
  
    &lt;%= submit_tag "Edit Trade" %&gt;
  &lt;% end %&gt;
  </code></pre>