2011-03-29 55 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 %> 

祝你好運!

相關問題