2014-05-02 18 views
29

我對rails有點新,我正在嘗試創建一個用戶登錄。我通過教程發現here。最後,我添加了「attr_accessible」進行批量分配。然而,當我這樣做,我得到了以下錯誤:未定義的方法attr_accessible

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

我對這個post我neeed <的ActiveRecord :: Base的看到。但我確實包括這一點。這裏是我的用戶模型代碼:

class User < ActiveRecord::Base 

    attr_accessor :password 
    EMAIL_REGEX = /\A[A-Z0-9._%+-][email protected][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 

任何其他想法是什麼可能會導致這個問題將非常感激,謝謝!

編輯:On Rails 4.1。看起來它不再適用。由於fotanus

+4

[這裏閱讀](http://stackoverflow.com/questions/17371334/how-is-attr-accessible-used-in-rails-4)。用你正在使用的正確的rails版本修正你的問題,因爲這對於這個問題很重要。 – fotanus

回答

74

允許爲Rails 4.1

,而不是在你的模型具有attr_accessible :username, :email, :password, :password_confirmation,用strong parameters無質量分配。 您將在UsersController做到這一點:

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

然後調用user_params方法在你的控制器動作。

15

沒有質量分配允許的Rails 4.1

你將不得不嘗試這樣的事情。

class Person 
    has_many :pets 
    accepts_nested_attributes_for :pets 
end 

class PeopleController < ActionController::Base 
    def create 
    Person.create(person_params) 
    end 

    ... 

    private 

    def person_params 
     # It's mandatory to specify the nested attributes that should be whitelisted. 
     # If you use `permit` with just the key that points to the nested attributes hash, 
     # it will return an empty hash. 
     params.require(:person).permit(:name, :age, pets_attributes: [ :name, :category ]) 
    end 
end 

參考

https://github.com/rails/strong_parameters

2

確保您安裝了寶石 'protected_attributes',這種寶石出現在你的Gemfile和運行bundle install終端。然後重新啓動服務器。