pixelearth
pixelearth

Reputation: 14630

Is there a 'declarative' way to authorize which attributes of a model can be changed?

The use of attr_accessible isn't quite sufficient as it is either on or off.

Some models have user forms, and also admin forms. For the admins the attributes they need to be able to mass-assign need to be in attr_accessible, but that means that a normal user could inject those params maliciously. It seems like a lot of work to manually assign everything on the admin side, and attr_accessible to those attributes that normal users can alter.

Is there a rails-centric standard solution to this issue? Maybe a gem?

I envision something like this:

model.update_attributes_with_user(params[:model], user)

Upvotes: 1

Views: 95

Answers (2)

emrass
emrass

Reputation: 6444

I recommend you read this official blog post on setting mass-assignable attributes in the controller: http://weblog.rubyonrails.org/2012/3/21/strong-parameters/

It also links to the gem that helps implementing the so-called slice-pattern (or an extraction thereof): https://github.com/rails/strong_parameters

This solution lets you specify the editable attributes in your users controller and admin_users controller differently.

Upvotes: 1

MrDanA
MrDanA

Reputation: 11647

You want the :as option for attr_accessible.

See this Rails doc for more information and examples.

As a quick example though (from the link):

 attr_accessible :name, :credit_rating, :as => :admin
 customer.assign_attributes({ "name" => "David", ... }, :as => :admin)

Upvotes: 1

Related Questions