2011-03-29 56 views
0

我无法解决这个错误。无法弄清楚为什么@客户被赋值为零。ruby​​中nil.update_attributes的解决方案是什么?

“你有一个零对象时,你没想到吧! 你期望的ActiveRecord :: Base的实例。 在评估nil.update_attributes发生错误”

这里是一个片段代码:

def cedit 
    @title = "Edit Customer Information" 
    @customer = Customer.find(params[:id]) 
    if request.post? and params[:customer] 
    attribute = params[:attribute] 
    case attribute 
     when "fname" 
     try_to_update @customer, attribute 
     when "email" 
     try_to_update @customer, attribute 
     when "add" 
     try_to_update @customer, attribute 
    end 
    end 
end 


private 
    def try_to_update(customer, attribute) 
    if customer.update_attributes(params[:customer]) 
     flash[:notice] = "Customer's details updated." 
     redirect_to :action => "record", :controller => "c2" 
    end 
    end 
+0

你确定你正在做一个post请求,并且在params中有一个'customer',你确定你没有在寻找'id'吗? – ThoKra 2011-03-29 10:26:48

+0

为什么你打破了REST的概念?我建议你阅读一本关于导轨的书。 – dombesz 2011-03-29 10:31:55

+0

是的,我有一个参数的客户。我为另一个动作和控制器使用了类似的代码。它在那里工作正常.. – Mukul 2011-03-29 10:35:27

回答

1

首先你的代码看起来很像非轨,并且打破了一些轨道的最佳实践。我强烈建议你阅读official Rails guide并尝试查看是否可以重构一些代码。

我对你在大规模的事情上试图做什么的信息太少,所以我不能给你一个完整的答案。但是你可能想要按照这些方法做一些事情。

class CustomersController < ApplicationController 
    def update 
    @customer = Customer.find(params[:id]) 
    if @customer.update_attributes(params[:customer]) 
     flash[:notice] = "Customer updated" 
    end 
    redirect_to customer_path(@customer) 
    end 
end 

的观点可能是这个样子:

<%= form_for(:customer) do |f| %> 
    <%= f.text_field :fname %> 
    <%= f.text_field :email %> 
    <%= f.text_field :add %> 
    <%= f.submit_tag "Update" %> 
<% end %> 

祝你好运!

相关问题