根據rails-cast #237,動態屬性很容易實現。雖然我試圖在rails控制檯中創建一個對象時遇到了一些錯誤。請指教。動態attr_accessible in rails
我得到的錯誤如下:
ruby-1.9.3-p0 :005 > User.new :username => "johnsmith", :email => "[email protected]", :password => "changethis"
ArgumentError: wrong number of arguments (1 for 0)
from /Volumes/Terra-Nova/jwaldrip/Sites/theirksome/config/initializers/accessible_attributes.rb:6:in `mass_assignment_authorizer'
from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.1.3/lib/active_model/mass_assignment_security.rb:209:in `sanitize_for_mass_assignment'
from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.1.3/lib/active_record/base.rb:1744:in `assign_attributes'
from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.1.3/lib/active_record/base.rb:1567:in `initialize'
from (irb):5:in `new'
from (irb):5
from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in `start'
from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in `start'
from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.1.3/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
/models/user.rb:
class User < ActiveRecord::Base
# Attributes
attr_accessible :username, :email, :password, :password_confirmation, :is_admin
attr_accessor :password
# Callbacks
before_save :encrypt_password
# Relationships
has_many :irks
# Validation
validates_confirmation_of :password
validates_presence_of :password, on: :create
validates :password, presence: true, length: { in: 3..20 }
validates :username, presence: true, uniqueness: true, length: { in: 3..20 }
validates :email, presence: true, email: true, uniqueness: true
# User Authentication
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
# Password Encryption
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
/config/initializers/accessible_attributes.rb:
class ActiveRecord::Base
attr_accessible
attr_accessor :accessible
private
def mass_assignment_authorizer
if accessible == :all
self.class.protected_attributes
else
super + (accessible || [])
end
end
end
我試圖完成的唯一事情是根據您的權限使某些屬性可訪問。又名當你擁有這個對象時,或者你是一個管理員。 – 2011-12-29 20:54:58
看完railscast並重新閱讀說明後,我改變了我的看法。我認爲這是一個明智的解決方案。這就是說,它看起來好像railscast已經過時並且不兼容'rails 3.1'。 [我會閱讀attr_accessible爲ActiveRecord的版本的rails你正在使用的文檔](http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.Mtml#method-i-attr_accessible)。看起來它已經變得更容易了,您正在使用的模塊是不必要的,因爲您現在可以定義哪些屬性可以在每個角色的基礎上訪問。 – Batkins 2011-12-29 21:54:51