Unfortunately this works: ROR Comparison in Activerecord - update
Unfortunately this mess works: Do you have suggestings for cleaning up this code: I'm trying to use a activerecord to compare two table columns, "needed" and "amount" then update a boolean column, depending on the returned data. Totally breaking do-not-repeat coding.
def update
@inventory = Inventory.find(params[:id])
r开发者_Python百科espond_to do |format|
if @inventory.update_attributes(params[:inventory])
unless @inventory.needed.nil?
if @inventory.needed < @inventory.amount then
@inventory.instock = true
@inventory.update_attributes(params[:inventory])
else
@inventory.instock = false
@inventory.update_attributes(params[:inventory])
end
end
flash[:notice] = 'Inventory was successfully updated.'
format.html { redirect_to(@inventory) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @inventory.errors, :status => :unprocessable_entity }
end
end
end
Cheers!
First, keep the extraneous logic out of your controller:
def update
@inventory = Inventory.find(params[:id])
respond_to do |format|
if @inventory.update_attributes(params[:inventory])
flash[:notice] = 'Inventory was successfully updated.'
format.html { redirect_to(@inventory) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @inventory.errors, :status => :unprocessable_entity }
end
end
end
Then, handle the instock attribute with a callback on the Inventory model. Something like:
before_update :check_instock, :unless => Proc.new { |inventory| inventory.needed.nil? }
def check_instock
if needed < amount
instock = true
else
instock = false
end
end
Very confused by your multiple calls to @inventory.update_attributes
. You should only call that once when the records should be saved to the database. You should use @inventory.attributes = params[:inventory]
and use if @inventory.save
to hit the database.
Perhaps something like (untested):
@inventory.attributes = params[:inventory]
unless @inventory.needed.nil?
@inventory.instock = (@inventory.needed < @inventory.amount) ? true : false
@inventory.save
end
精彩评论