![](/img/trans.png)
[英]ActionController::RoutingError (undefined method `attr_accessible')
[英]Undefined Method attr_accessible
我對rails很新,我正在嘗試創建用戶登錄。 我瀏覽了這里的教程。 最后它讓我為質量分配添加“attr_accessible”。 但是,當我這樣做時,我收到以下錯誤:
undefined method `attr_accessible' for #<Class:0x007ff70f276010>
我在這篇文章中看到我需要<ActiveRecord :: Base。 但我確實包含了這一點。 這是我的用戶模型的代碼:
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
關於可能導致這個問題的任何其他想法將非常感謝,謝謝!
編輯:On Rails 4.1。 看起來它不再適用了。 謝謝fotanus
Rails 4.1不允許批量分配
而不是在模型中使用attr_accessible :username, :email, :password, :password_confirmation
,而是使用強參數 。 您將在UsersController中執行此操作:
def user_params
params.require(:user).permit(:username, :email, :password, :password_confirmation)
end
然后在控制器操作中調用user_params方法。
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
參考
確保你安裝了gem'en protected_attributes',這個gem存在於你的gemfile中並運行bundle install
terminal。 然后重啟服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.