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 valu开发者_如何学Goes 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?
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
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
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
精彩评论