Unfortunately this works: ROR Comparison in Activerecord - update

会有一股神秘感。 提交于 2019-12-12 04:44:23

问题


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])

    respond_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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/1760224/unfortunately-this-works-ror-comparison-in-activerecord-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!