I have a contact form partial that I include in two different forms on my app. I was wondering if there is a better approach to strong parameters than duplicating the permitted params in each respective controller?
Users controller:
def user_params
params.require(:user).permit(:name, :email, contact_attributes: [:city, :state])
end
User Applications controller:
def user_application_params
params.require(:user_application).permit(:gender, :birthdate,
user_attributes: [contact_attributes: [:city, :state]])
end
So ideally this code would be in one place, I'm not sure how to achieve this though.
First, let me say, whitelisting your all params automatically is a hack that might be ok in some situations but could cause some substantial security risks in others and exposes you to risk as your codebase evolves (so it's never really ok). Here's a much better way to solve the problem that is about as easy and should work in just about all situations.
Instead, write a controller concern. This is just a module that goes into your app/controllers/concerns
directory.
so create app/controllers/concerns/shared_contact_permitted_attributes.rb
as follows:
module SharedContactPermittedAttributes
def shared_contact_permitted_attributes
contact_attributes: [:city, :state]
end
end
Then in whatever controller you want it to show up in, add include SharedContactPermittedAttributes
at the top and use the method defined in the module in your strong params. For example:
def user_params
params.require(:user).permit(:name, :email, shared_contact_permitted_attributes)
end
Then you're done!