Rails 4 Strong parameters : permit all attributes?

Ruby on-RailsRuby on-Rails-3Strong Parameters

Ruby on-Rails Problem Overview


I'm building a web app with Rails 4 strong parameters.

When building the admin back office controllers, I wonder what is the best way to permit all the model attributes?

For now, I wrote this:

def user_params 
  params.require(:user).permit(User.fields.keys)
end

Do you think of a better way?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can call the bang version of permit.

params.require(:user).permit!

Strong Params README on Github

Source code for reference:

def permit!
  each_pair do |key, value|
    convert_hashes_to_parameters(key, value)
    self[key].permit! if self[key].respond_to? :permit!
  end

  @permitted = true
  self
end

Solution 2 - Ruby on-Rails

Just in case someone need it for Rails 6, without even a model linked to your controller, you can use:

before_action :accept_all_params

private

def accept_all_params
  params.permit!
end

And done, now you can play with  as much as you want!

Solution 3 - Ruby on-Rails

Skull0inc's answer works, but you might want to remove created_at and updated_at. The intention of strong params is to list only the attributes you want updatable by the controller. Something like...

def user_params
  params.require(:user).permit(User.column_names - ["created_at", "updated_at"])
end

Solution 4 - Ruby on-Rails

Would this work?

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicolas BlancoView Question on Stackoverflow
Solution 1 - Ruby on-RailsDamon AwView Answer on Stackoverflow
Solution 2 - Ruby on-RailsvvoView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAnthony SallowsView Answer on Stackoverflow
Solution 4 - Ruby on-RailsSkull0incView Answer on Stackoverflow