iamprogram
iamprogram

Reputation: 23

Rails 3 - Calculated column

I want to create a calculated field that multiply column1 and column2 on rails 3.

Like this :

totalpoint = column1 * column2

Where is I have to place the code? in the model? How do I write it?

How do I call it from my view?

Upvotes: 2

Views: 3437

Answers (2)

deefour
deefour

Reputation: 35350

I think this is better placed on the model

attr_reader :totalpoint

def totalpoint
  column1 * column2
end

Give some instance @m of your model, it can be accessed anywhere (in an action, in the view, etc..) as

@m.totalpoint

You can access this from within the model simply with

@totalpoint

Upvotes: 6

Veger
Veger

Reputation: 37906

In your controller create put the calculation in a instance variable (starts with @) in the action that is being called, eg index:

def index
  @totalpoint = column1 * column2
end

In your view (index.html.erb) you can use the instance variable:

<div>
  Total point = <%= @totalpoint %>
</div>

If you need to do this for multiple rows, you can use an array and use it in your view.

Upvotes: 1

Related Questions