2013-01-18 45 views

回答

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") 
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 
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 

5.4 Grouping conditional validations

HTH

相關問題