2

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?

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.