Rails wraps your parameters into an interface called StrongParameters Show archive.org snapshot . In most cases your form submits you data in a nested structure, which goes hand in hand with strong parameter interface.
Example:
curl -X POST -d "user[name]=bob" https://example.com/users
class UsersController
def create
User.create!(params.expect(user: [:name]) # Or User.create!(params.require(:user).permit(:name)
end
end
Most of the time you are using the params
object within your application the patter above works for you. But there are cases, where this pattern doesn't work and you have to be extra careful about your written code. Here are some examples with fixes.
# Okay
User.find(params[:id])
# Better
User.find(params.expect(:id)) # Or User.find(params.require(:id))
# Bad (logs or raises errors with other params e.g. page=1)
redirect_to users_path(params.permit(:query, :encoding))
# Better
redirect_to users_path(params.slice(:query, :encoding).permit(:query, :encoding))
# Dangerous, see https://makandracards.com/makandra/608868-permit-params
User.create!(params.permit!)
# Better
User.create!(params.expect(user: [:name])
# Dangerous, see https://makandracards.com/makandra/608875-pass-params-directly-url-url-helpers
url_for(params.to_unsafe_h)
# Better
url_for(path_params: request.path_parameters, params: request.query_parameters)
It's also worth to read Rails: Using require and permit for attributes when configuring your application.
Posted by Emanuel to makandra dev (2025-01-27 10:53)