是否可以使用attr_accessible
和attr_protected
使用的角色?我正在尝试设置仅在不是管理员时执行的验证(如此类http://launchware.com/articles/whats-new-in-edge-scoped-mass-assignment-in-rails-3-1)。例如:
class User < ActiveRecord::Base
def validate(record)
unless # role.admin?
record.errors[:name] << 'Wrong length' if ...
end
end
end
user = User.create({ ... }, role: "admin")
答案 0 :(得分:1)
在查看并深入挖掘源代码之后,看起来创建Active Record对象时传入的角色是通过受保护的方法mass_assignment_role
公开的。因此,有问题的代码可以重写为:
class User < ActiveRecord::Base
def validate(record)
unless mass_assignment_role.eql? :admin
record.errors[:name] << 'Wrong length' if ...
end
end
end
user = User.create({ ... }, role: "admin")
答案 1 :(得分:0)
肯定会是这样的:
class User < ActiveRecord::Base
attr_accessible :role
validates :record_validation
def record_validation
unless self.role == "admin"
errors.add(:name, "error message") if ..
end
end
答案 2 :(得分:0)
你可以这样做
class User < ActiveRecord::Base
with_options :if => :is_admin? do |admin|
admin.validates :password, :length => { :minimum => 10 } #sample validations
admin.validates :email, :presence => true #sample validations
end
end