0

I'm working on a simple rails app. The user enters two separate integers and when they press 'create', the 'show' page displays the two values and a third value which is calculated from the user input. I have put the arithmetic to calculate the third value in the 'show' html.erb view, but I can't work out how to add the third value into the database. Heres my code for the 'show' view:`

Name: <%= @startup.name %>

<p>
<strong>Revenue:</strong>
<%= @startup.revenue %>
</p>

<p>
<strong>Costs:</strong>
<%= @startup.costs %>
</p>
<h2>
<strong>Profit:</strong>
<%= @startup.profit = @startup.revenue - @startup.costs %>
SJDuk
  • 43
  • 1
  • 1
  • 5
  • If you want to save `profit` into separate column, do it in model callback or in controller action. Views are not the best place to change model properties. – dimakura Sep 30 '15 at 20:44
  • Possible duplicate of [Populating Rails Fields Based on Calculation](http://stackoverflow.com/questions/13261762/populating-rails-fields-based-on-calculation) – Brad Werth Sep 30 '15 at 20:44

2 Answers2

0

You could add a column to the database for this calculated value, and update it upon completing the calculation.

Create a migration to add the column profit to the startup model:

rails g migration AddProfitToStartups profit:decimal

with a note that you may choose a different datatype for profit depending on what datatype your revenue and costs columns are. There are other helpers for currency, see here.

This will generate:

class AddProfitToStartups < ActiveRecord::Migration
  def change
    add_column :startups, :profit, :decimal
  end
end

now run rake db:migrate to update the database.

After this, the code you have in your view should work as is.

Community
  • 1
  • 1
andrewcockerham
  • 2,676
  • 3
  • 23
  • 19
-1

Create a variable in the Startup model call profit. In the create action have something like this:

def create
  @startup = Startup.new(startup_params)
  @startup.profit = @startup.revenue - @startup.costs
  @startup.save
  #redirect
end

Apparently the above answer is bad practice. So, here is what I hope is a better more general solution.

At the top of your Startup model have a call to before_save that will look like this:

before_save :calculate_profit

and then write a function in the Model called calculate profit. It will look something like this

def calculate_profit
  self.profit ||= self.revenue - self.costs
end
userFriendly
  • 474
  • 3
  • 14