Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Roles for Validations in Rails

Is it possible to use the roles used for attr_accessible and attr_protected? I'm trying to setup a validation that only executes when not an admin (like this sort of http://launchware.com/articles/whats-new-in-edge-scoped-mass-assignment-in-rails-3-1). For example:

class User < ActiveRecord::Base
   def validate(record)
     unless # role.admin?
       record.errors[:name] << 'Wrong length' if ...
     end
  end
end

user = User.create({ ... }, role: "admin")
like image 728
Kevin Sylvestre Avatar asked Dec 22 '25 16:12

Kevin Sylvestre


1 Answers

After looking into this and digging through the source code, it appears that the role passed in when creating an Active Record object is exposed through a protected method mass_assignment_role. Thus, the code in question can be re-written as:

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")
like image 149
Kevin Sylvestre Avatar answered Dec 24 '25 07:12

Kevin Sylvestre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!