Rails 3 Table with Fields Using Calculated Data
I have a table in my app, called entries. Entries belongs_to :users and has a field (decimal) called hours. There is another decimal field called cost. Cost is not entered by the user, but is calculated by multiplying the value in hours with the value in users named rate. To get this to work properly, I had to do the following.
First, in the entry form, make sure there is no text_field for cost. Cost is only found using a calculation.
In entries_controller.rb, edit create and update as follows:
def create @entry = Entry.new(params[:entry]) @entry.cost = @entry.user.rate * @entry.hours respond_to do |format| if @entry.save format.html { redirect_to(@entry, :notice => 'Entry was successfully created.') } else format.html { render :action => "new" } end end end def update @entry = Entry.find(params[:id]) total_cost = @entry.user.rate * @entry.hours @entry.update_attribute(:cost, total_cost) respond_to do |format| if @entry.update_attributes(params[:entry]) format.html { redirect_to(@entry, :notice => 'Entry was successfully updated.') } else format.html { render :action => "edit" } end end end
There should be a way to put a method in the model to calculate the total_cost, but I haven’t successfully figured that out yet.