Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

ruby on rails - Undefined Method attr_accessible

I am somewhat new to rails and I am trying to create a User login. I went through the tutorial found here. At the end it had me add "attr_accessible" for mass assignment. However when I did that I got the following error:

undefined method `attr_accessible' for #<Class:0x007ff70f276010>

I saw on this post that I neeed < ActiveRecord::Base. But I do have that included. Here is the code for my User Model:

class User < ActiveRecord::Base

  attr_accessor :password
  EMAIL_REGEX = /A[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}z/i
  validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
  validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
  validates :password, :confirmation => true #password_confirmation attr
  validates_length_of :password, :in => 6..20, :on => :create
  before_save :encrypt_password
  after_save :clear_password
  attr_accessible :username, :email, :password, :password_confirmation

  def encrypt_password
    if password.present?
      self.salt = BCrypt::Engine.generate_salt
      self.encrypted_password= BCrypt::Engine.hash_secret(password, salt)
    end
  end

  def clear_password
    self.password = nil
  end

end

Any other ideas on what could be causing this problem would be really appreciated, thanks!

Edit: On Rails 4.1. Looks like it doesn't apply anymore. Thanks fotanus

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No mass assignment allowed for Rails 4.1

instead of having attr_accessible :username, :email, :password, :password_confirmation in your model, use strong parameters. You'll do this in your UsersController:

    def user_params
      params.require(:user).permit(:username, :email, :password, :password_confirmation)
    end

then call the user_params method in your controller actions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...