Search code examples
ruby-on-railsruby-on-rails-3devisecontrollerupdate-attribute

Using update_attribute and getting NoMethodError: undefined method `0=' for #<User:0x007fe470de2950


Problem statement

In my controller I am trying to change a boolean attribute not_registered in Update using resource.update_attribute(resource.not_registered, 1), but am getting NoMethodError: undefined method 0= for #<User:0x007fe470de2950. Any idea why this is happening? Appreciate any ideas you may have, this is the last bug I need to work out before completing this project, which will be my first in RoR!

My progress

  • I looked into using save instead, but can't because I need to skip validation. Also seems inefficient since I am only updating one attribute
  • In the shell, resource (created by Devise) appears to be an instance of the current User
  • Before executing the Update controller resource.not_registered => 0, which is correct... so I know that resource.not_registered is correct syntax.
  • If I run resource.update_attribute, I get !! #<ArgumentError: wrong number of arguments (0 for 2)> ... so I know that update_attribute exists as a method for resource
  • Finally, I found the documentation for update_attribute here.

Code

/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

Solution

  • Change following line

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

    to

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

    and read some solid Rails documentation. I suggest going through http://guides.rubyonrails.org/index.html