不幸的是这个工程:ROR比较中的ActiveRecord - 更新 [英] Unfortunately this works: ROR Comparison in Activerecord - update

查看:359
本文介绍了不幸的是这个工程:ROR比较中的ActiveRecord - 更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是这个烂摊子的工作原理:你有suggestings清理这个code:我想用一个ActiveRecord的比较两个表列,需要和量,然后更新一个布尔值列,这取决于返回的数据。完全打破这样做,不重复的编码。

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

干杯!

推荐答案

首先,保持外部逻辑移出控制器:

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

然后,处理好与对库存模型回调的属性的inStock。是这样的:

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

这篇关于不幸的是这个工程:ROR比较中的ActiveRecord - 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆