1

Lets supose I have a User table, and on this table I have height, weight and result rows. In a form I input height and weight values and want to multiply those two values and store on the resulta row on database. I was trying something like that

  def create
    @user = User.new(params[:user])
    @result = @user.height * @user.weight
    @user.result = @result

But its not working, what am i doing wrong?

1
  • 1
    "But its not working" What isn't working? What happens? What are the errors? Did you save after these modifications? Commented Aug 18, 2011 at 17:53

3 Answers 3

2

I think it would be nicer to have the computation done on a before_save filter on the model. Using the first 2 answers, it should look like this:

users_controller.rb

def create
  @user = User.new(params[:user])
  if @user.save
    redirect_to @user
  else
    render :action => :new
  end
end

user.rb

before_save :compute_result

def compute_result
  result = height * weight
end
Sign up to request clarification or add additional context in comments.

Comments

1

You'd better put this logic (multiply) into your model, write a method for :before_save

That's the Rails Way!

See this API documentation: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Comments

0

Make sure that params[:user] has values for :height & :weight keys. If yes, then you should set the fields height & weight as attr_accessible like this:

user.rb

class User < ActiveRecord::Base
  attr_accessor :height, :weight
end

users_controller.rb

def create
    @user = User.new(params[:user])
    @result = @user.height * @user.weight
    @user.result = @result
    if @user.save
      redirect_to @user
    else
      render :action => :new
    end
end

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.