Q:

Rails how loop a calcuation and create a "fake" column?

I want to loop a calculation that is based on users params.
Example in my index action I have:
@com = Company.where(:online => true).order('position')

And I my table I have:
Name (varchar)
Price1 (integer)
Price2 (integer)
Price1in (integer)
Price2in (integer)

In view I then have my simple loop:
<%= com.name %><br />
<%= com.price1 %><br />
<%= com.price2 %>

I have created a instance method to do some calculation. 
Model:
  def sum_price(x)
    (((x - self.price1in) * (60 * self.price1)) / 100))
  end

   def sum_price2(x)
    (self.price2 * x / 100)
  end

I can now do:
<% @com.each do |com| %>

    <%= com.name %><br />
    <%= com.price1 %><br />
    <%= com.price2 %><br />
    <%= com.sum_price(params[:price]) %><br />
    <%= com.sum_price2(params[:price2]) %>
<% end %>

But I want to order by total_price which is com.sum_price2(params[:price]) + com.sum_price2(params[:price2]) and I want to be able to call it in view as:
<% @com.each do |com| %>
    <%= com.name %><br />
    <%= com.total_price %><br />
<% end %>

A:

This should work:
class Company
  include Comparable
  attr_accessor :total_price

  def <=> other
    self.total_price <=> other.total_price
  end

  def sum_price(x)
    (((x - self.price1in) * (60 * self.price1)) / 100))
  end

  def sum_price2(x)
    (self.price2 * x / 100)
  end

  def calculate_total price1, price2
    @total_price ||= sum_price(price1) + sum_price2(price2)
  end
end

#controller
@companies = Company.all
@companies.each{|company| company.calculate_total(params[:price], params[:price2])}
@companies.sort!

