Dustin James
Dustin James

Reputation: 571

Sum DB fields in Rails

In my rails app I have a Jobs model. In the Jobs model there are three separate fields in the Job record that I want to sum - cabinetry_cost, counter_top_cost and install_cost.

To do so, I have the following method in my jobs model:

def revenue
  job_by_id = Job.find(params[:id])
  revenue = job_by_id.sum(:cabinet_cost + :counter_top_cost + :install_cost)
end

In my view, I am calling the method as follows (using job.revenue below):

<% @customer.jobs.each do |job| %>
  <tr>
    <td><%= link_to job.id, customer_job_path(@customer, job) %></td>
    <td><%= job.job_tag %></td>
    <td></td>
    <td><%= job.install_date %></td>
    <td><%= job.revenue %></td>
  </tr>
<% end %>

Currently, I am getting the following error:

undefined local variable or method `params'  

Does anyone know what I am missing?

Upvotes: 0

Views: 61

Answers (1)

Jaugar Chang
Jaugar Chang

Reputation: 3196

You don't need to sum any thing in your model, just add them.

Class Job <  ActiveRecord::Base
  def revenue
    cabinet_cost + counter_top_cost + install_cost
  end
end

params is the variable came from your view, should be used in your controller, not in your model. You should step back to learn some thing about Rails framework first.

Upvotes: 2

Related Questions