ovatsug25
ovatsug25

Reputation: 8606

how can I check which attributes are accessible for my Rails app?

I am doing some metaprogramming where I add accessible attributes to a model and would like to know how to check and see whether these attributes are accessible.

Looked at the documentation but could find no reference.

http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible

I know I can do something like object.instance_methods but that dozen't really filter it down to accessible.

Is there some method that will return the accessible attributes?

Upvotes: 0

Views: 338

Answers (2)

Jellicle
Jellicle

Reputation: 30256

Use accessible_attributes and protected_attributes.

class User < ActiveRecord::Base
  attr_accessible :first_name, :last_name
end

User.accessible_attributes
# => #<ActiveModel::MassAssignmentSecurity::WhiteList: {"", "first_name", "last_name"}>

User.protected_attributes
# => #<ActiveModel::MassAssignmentSecurity::BlackList: {"id", "type"}>

If you call attr_protected and not attr_accessible in your class, then ALL of your attributes except for those in your Blacklist will be accessible.

Upvotes: 1

CupraR_On_Rails
CupraR_On_Rails

Reputation: 2489

Assuming you have a User model with these attributes: :id, :lastname, :firstname, :email and your model class is:

class User < ActiveRecord::Base
  attr_accessible :lastname, :firstname
end

You can have the accessible list like this:

User.attr_accessible[:default].to_a
=> [:lastname, :firstname]

Moreover you can have the list of no-accessible attributes:

User.new.attributes.keys - User.attr_accessible[:default].to_
=> [:id, :email]

I hope this help

Upvotes: 0

Related Questions