0

In a controller's update action, I have:

entry.update_attributes(params[:entry])

There are some keys in params[:entry] that either correspond to non-accessible fields, or no field at all. If I don't have control over the values in params[:entry], how can I filter it so that only accessible fields for the relevant model remain in it, presumably by accessing a list of the whitelisted attributes for the model? I know how to exclude/include keys from a hash, but I don't want to manually define the keys to include/exclude, because then I'd be duplicating the whitelist when it's already defined in the model.

I'm using Rails 3.2.13.

ben
  • 29,229
  • 42
  • 124
  • 179

3 Answers3

2

http://apidock.com/rails/Hash/except

except(*keys) public

Return a hash that includes everything but the given keys. This is useful for limiting a set of parameters to everything but a few known toggles:

@person.update_attributes(params[:person].except(:admin))
SG 86
  • 6,974
  • 3
  • 25
  • 34
1

Its default in Rails 4, so you should use it :)

It also works in Rails 3: https://github.com/rails/strong_parameters

BvuRVKyUVlViVIc7
  • 11,641
  • 9
  • 59
  • 111
1

For those looking to the answer to the question of filtering a hash so it has only a selected set of keys, using rails slice method for Hash works along with the accessible attributes of the model.

@person.update_attributes(params[:person].only(*Person.attr_accessible[:default]‌​.to_a))

I think there's likely a neater way to do this, welcome suggestions.

ChrisJ
  • 2,486
  • 21
  • 40