0

I've got a Rails 3.1 app using CanCan 1.6. I'm protecting a variety of attributes with attr_protected ... :as => :api. I'd like to use load_and_authorize_resource, but also to strip off the protected fields. Any ideas?

EDIT: Here's my current workaround:

In orders#new, I'm skipping the load_resource and just authorizing. I initialize the new order directly, with the appropriate scope:

@order = Order.new(params[:order], :as => :api)

Then setting the user manually:

@order.user = current_user

Certainly not a huge deal to do, but less elegant than just letting CanCan load and authorize natively, as I'm doing elsewhere.

ideaoforder
  • 1,023
  • 2
  • 9
  • 23

1 Answers1

0

Generally if you only have a few protected fields to submit for, it would just be easier to pull the value out of the parameter hash and manually assign it.

##save the parameter and delete it from the hash
role      = params[:employee][:role_id]
params[:employee].delete("role_id")

##create object and assign parameter manually
@employee = Employee.new(params[:employee])
@employee.role_id = role

If you have a lot of attributes, you could automate the manual assignment.

##list protected attributes and create new employee
attr = Employee.protected_attributes ##["id", "type", "name"]

@employee = Employee.new

##loop through params and manually send value
params[:employee].each do |p|
    @employee.send("#{p}=", params[:employee]["#{p}"])
end

Didn't have time to fully test the second part, but that should get you in the right direction.

Kosmonaut
  • 2,154
  • 2
  • 18
  • 19
  • Thanks for the insight Kosmonaut. Unfortunately, this solution won't work with nested resources which, in this case, I'm actually using. I've updated my post above with my current workaround, but I was hoping for something a bit more elegant than my workaround. If not for the nesting, your solution would have worked just fine. – ideaoforder Aug 01 '12 at 16:41