简体   繁体   中英

Rails 4 Strong Parameters : can I 'exclude' / blacklist attributes instead of permit / whitelist?

I'm migrating a Rails 3 app to Rails 4 and I'm in the process of converting attr_accessible properties to strong parameters in the controller. The API Documentation shows how to 'permit' attributes:

def person_params
  params.require(:person).permit(:name, :age)
end

However the vast majority of my attributes are mass-assignment safe. It's only a few attributes like :account_id and :is_admin that I need to blacklist.

Is it possible to blacklist attributes instead of whitelisting almost every attribute? Eg something like:

def user_params
  params.require(:user).exclude(:account_id, :is_admin)
end

I think you shouldn't really do that for reasons outlined by @Damien, but heres a solution I just found.

params.require(:user).except!(:account_id, :is_admin).permit!

This will remove :account_id, :is_admin from hash and permit all other parameters. But again - this is potentially insecure.

Why this works? Because ActionController::Parameters inherits from Hash !

Update 4th July 2016

In Rails 5 this probably doesn't work anymore as per upgrade guide

ActionController::Parameters No Longer Inherits from HashWithIndifferentAccess

No, this is not possible.
Blacklisting attributes would be a security issue, since your codebase can evolve, and other attributes, which should be blacklisted can be forgotten in the future.

Adding all your whitelisted attributes might seem like a complicated thing when implementing it.
However, it's the only way of keeping your application secure and avoiding disturbing things .

Whitelisting is more secure.

But u can try: In model:

self.permitted_params
  attribute_names - ["is_admin"]
end

In Controller:

def user_params
  params.require(:user).permit(*User.permitted_params)
end

From the docs : yes, you can, with except , which "returns a new ActionController::Parameters instance that filters out the given keys":

params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
params.except(:a, :b) # => <ActionController::Parameters {"c"=>3} permitted: false>
params.except(:d)     # => <ActionController::Parameters {"a"=>1, "b"=>2, "c"=>3} permitted: false>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM