Undefined method attr_accessible error for User

12,409

attr_accessible is not available for Rails version 4+. You would have to go with strong parameters.

With Strong Parameters, attribute whitelisting has been moved to controller level. Remove the attr_accessible call from your model.

Here is an example in Rails Guide of how to use Strong Parameters

In your case you can do something like this:

class UsersController < ApplicationController
  ## ...
  def create
    @user = User.new(user_params) ## Invoke user_params method
    if @user.save
      redirect_to @user, notice: 'User was successfully created.' 
    else
      render action: 'new'
    end       
  end
  ## ... 

  private
  ## Strong Parameters 
  def user_params
    params.require(:user).permit(:name, :password_digest, :password, :password_confirmation)
  end
end 

You can take a note of @Frederick comment below my answer,

you can still use attr_accessible but it has been extracted into the protected_attributes gem (although clearly strong parameters is the way forwards)

Share:
12,409
Admin
Author by

Admin

Updated on June 11, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm trying to create a login of sorts. I created a User scaffold and have this code in my user.rb

    class User < ActiveRecord::Base
    attr_accessible :name,  :password_digest, :password, :password_confirmation
    
    has_secure_password
    end
    

    I keep getting this error

    undefined method `attr_accessible' for #<Class:0x396bc28>
    
    Extracted source (around line #2):
    1
    2
    3
    4
    5
    
    class User < ActiveRecord::Base
      attr_accessible :name,  :password_digest, :password, :password_confirmation
    
      has_secure_password
    end
    
    Rails.root: C:/Sites/web
    
  • Admin
    Admin almost 10 years
    How do I use has_secure_password with strong params?
  • Kirti Thorat
    Kirti Thorat almost 10 years
    Just permit the attributes :name, :password_digest, :password, :password_confirmation in the UsersController like shown in the example link I provided in answer.
  • Frederick Cheung
    Frederick Cheung almost 10 years
    You can still use attr_accessible but it has been extracted into the protected_attributes gem (although clearly strong parameters is the way forwards)
  • Kirti Thorat
    Kirti Thorat almost 10 years
    @FrederickCheung +1 That's a good point, added it to my answer.