【问题标题】:Using update_attribute and getting NoMethodError: undefined method `0=' for #<User:0x007fe470de2950使用 update_attribute 并获取 NoMethodError: undefined method `0=' for #<User:0x007fe470de2950
【发布时间】:2013-06-22 19:52:30
【问题描述】:

问题陈述

在我的控制器中,我尝试使用resource.update_attribute(resource.not_registered, 1) 在更新中更改布尔属性not_registered,但我得到NoMethodError: undefined method 0= for #&lt;User:0x007fe470de2950。知道为什么会这样吗?感谢您的任何想法,这是我在完成这个项目之前需要解决的最后一个错误,这将是我在 RoR 中的第一个!

我的进步

  • 我考虑改用save,但不能,因为我需要跳过验证。也似乎效率低下,因为我只更新一个属性
  • 在 shell 中,resource(由 Devise 创建)似乎是当前用户的一个实例
  • 在执行更新控制器resource.not_registered => 0 之前,这是正确的……所以我知道resource.not_registered 是正确的语法。
  • 如果我运行resource.update_attribute,我得到!! #&lt;ArgumentError: wrong number of arguments (0 for 2)&gt; ...所以我知道update_attribute作为resource的方法存在
  • 最后,我找到了 update_attribute here 的文档。

代码

/app/controllers/registrations_controller.rb:

class RegistrationsController < Devise::RegistrationsController
    def update
        if resource.update_with_password(params[resource_name])        
            resource.update_attribute(resource.not_registered, "1") # this is where I get my error message
            set_flash_message :notice, :updated
            sign_in resource_name, resource, :bypass => true
            redirect_to after_update_path_for(resource)
        else
            clean_up_passwords(resource)
            render "edit"
        end     
    end

    # Code removed for brevity
end

/app/models/user.rb:

class User < ActiveRecord::Base

  devise :database_authenticatable, :registerable, :token_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  attr_accessible :email, :password, :password_confirmation,
  :remember_me, :not_registered, :pay_method, :pay_desc, :email_instructions, :current_password

  def update_with_password(params={})
      # code removed for brevity
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 devise controller update-attribute


    【解决方案1】:

    更改以下行

    resource.update_attribute(resource.not_registered, "1") # this is where I get my error message
    

    resource.update_attribute(:not_registered, "1") # this is where I get my error message
    

    并阅读一些可靠的 Rails 文档。我建议通过http://guides.rubyonrails.org/index.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 2015-03-19
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      相关资源
      最近更新 更多