【问题标题】:What's the solution for nil.update_attributes in ruby?ruby 中 nil.update_attributes 的解决方案是什么?
【发布时间】:2011-03-29 10:24:12
【问题描述】:

我无法破解此错误。无法弄清楚为什么 @customer 被分配为零值。

“当你没有预料到它时,你有一个 nil 对象! 您可能期望 ActiveRecord::Base 的实例。 评估 nil.update_attributes 时发生错误"

这是一个sn-p的代码:

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

【问题讨论】:

  • 你确定你正在做一个发布请求并且在参数中有一个customer,你确定你不是在寻找id吗?
  • 你为什么要打破 REST 概念?我建议你读一本关于 Rails 的书。
  • 是的,我在 params 中有一个客户。我正在为另一个动作和控制器使用类似的代码。那里工作正常..
  • 你能告诉我我破坏了哪些 REST 概念吗?我是 RoR 的新手。
  • @mukul...你确定这是代码吗..@customer 中是否有错字在你打电话给try_to_update @customer, attribute 的任何地方

标签: ruby-on-rails ruby null


【解决方案1】:

首先,您的代码看起来非常不像 Rails,并且违反了几个 Rails 最佳实践。我强烈建议您阅读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 %>

祝你好运!

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 2013-07-03
    • 2019-03-09
    • 1970-01-01
    • 2013-08-02
    • 2019-08-30
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多