I''m just learning Rails and have encountered a problem trying to set
a field in a DB record based on the value of another form input
field. Using the scaffold code, the create works as expected and the
update (edit) also works. However, one of the DB fields (amount) is
supposed to be computer from another (units): if the category field
is "Mileage", amount= units * Fed_mileage_rate, otherwise amount=
units.
To accomplish this, I removed the amount field from the input form,
as it is never entered directly, and put in an if statement to
accomplish the computation above. When I test this by doing a create
or an update, and units field is correct, but the amount is not.
(Strangely, it seems to me, if I repeat the update operation, the
amount is then correct.)
I feel that I may not be referring to the parameter or the DB field
correctly, or that update_attributes does not work as I expect.
I would appreciate it if someone with experience would look at this
and tell me what is wrong.
The scaffold code (with simple updates from the form with no
calculation) of the amount works:
def update
@expense = Expense.find(params[:id])
if @expense.update_attributes(params[:expense])
flash[:notice] = ''Expense was successfully updated.''
redirect_to :action => ''show'', :id => @expense
else
render :action => ''edit''
end
end
The modified code, which tries but fails to set calculate amount from
units is here:
def update
@expense = Expense.find(params[:id])
if @expense.category == "Mileage"
@expense.amount= @expense.units * Fed_mileage_rate
else
@expense.amount= @expense.units
end
if @expense.update_attributes(params[:expense])
flash[:notice] = ''Expense was successfully updated.''
redirect_to :action => ''show'', :id => @expense
else
render :action => ''edit''
end
end
Any enlightenment would be most welcomed.
Thanks,
Tom Bajzek