我有模型用户
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
attr_accessible :login, :email, :password, :password_confirmation ...
attr_accessible :role_ids, :active, :as => :super_admin
validates :email, :presence => true,
:format => {:with => /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i},
:uniqueness => {:case_sensitive => false},
:restricted_email_domain => true
...
end
以及用于前端和后端的两个单独的用户控制器。第一个非常微不足道,效果很好,第二个在下面
class Admin::UsersController < Admin::BaseController
def create
@user = User.new
@user.assign_attributes(params[:user], :as => :super_admin)
if @user.save
...
end
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user], :as => :super_admin)
...
end
end
我正在使用自定义验证器来检查用户的电子邮件域是否受到限制
class RestrictedEmailDomainValidator < ActiveModel::EachValidator
def validate_each(record, attr_name, value)
if !value.include?("@") # this value is nil if I add ":as => :super_admin"
record.errors.add(attr_name, :invalid, options.merge(:value => value))
else
domain = value.split("@")[1]
record.errors.add(attr_name, :restricted_email_domain, options.merge(:value => value)) if ::RestrictedEmailDomain.where(:domain => domain).exists?
end
end
end
module ActiveModel::Validations::HelperMethods
def validates_restricted_email_domain(*attr_names)
validates_with RestrictedEmailDomainValidator, _merge_attributes(attr_names)
end
end
更新操作效果很好,但创建操作You have a nil object when you didn't expect it!
在config/initializers/restricted_email_domain_validator.rb:3:in 'validate_each'
. 没有:as => :super_admin
一切都可以,但是当然role_ids
没有active
分配属性。
我可以手动赋值,但我认为这不是一个完美的解决方案。