Perform calculations in rails


Good I am new in rails I have the following doubt.

If I have a product model with cost and price, how would I calculate the price depending on the cost?

The serious price, cost * 30%

Is it done in the model or the constructor?

asked by develop12 01.11.2016 в 14:18

2 answers


You could create a method within your class Product in which you will perform the operation, and thus use the method instead of the direct operation.

Something like the following should work.

class Producto  
  def precio(sobrecosto)
    self.costo * (1.00 + sobrecosto)

In this way, you could directly get the price on each product. A benefit of this path, is that you could have a sobrecosto different per product, or even with a little more code, implement a global cost overrun for all your products, for example the 30% and eventually change it by modifying that number in a only place, instead of many others.

As you comment that you want new in rails, I am going to detail my answer a bit.

In the second line we are creating an instance method called precio that accepts an argument, in this case it is sobrecosto .

In line three, self refers to the object in which you are applying the method, then costo is the cost you have in your database for that product, sobrecosto is the value you want to give , for example 30% or 0.30.

Example of implementation:

manzana = Producto.create(costo: 100)
puts manzana
=> #<Producto:0x007ff2f823c858>

puts manzana.costo
=> 100

=> 130

I hope it serves you. Please, let me know if you have questions about this code.

answered by 01.11.2016 / 18:12

To add 30% of the cost:

total = costo + (costo * 0.3)


costo += costo * 0.3;
answered by 01.11.2016 в 17:25