0
0
Ruby on Railsframework~5 mins

Strong parameters in Ruby on Rails

Choose your learning style9 modes available
Introduction

Strong parameters help keep your app safe by only allowing certain data to be saved. This stops bad or unexpected data from sneaking in.

When you want to control which form data users can send to your server.
When creating or updating records in your Rails app to avoid unwanted changes.
When you want to prevent security risks like mass assignment attacks.
When handling data from external sources like APIs or user input forms.
Syntax
Ruby on Rails
params.require(:model_name).permit(:attribute1, :attribute2, ...)
Use require to specify the main key you expect in the parameters.
Use permit to list only the allowed attributes inside that key.
Examples
This allows only name and email from the user parameters.
Ruby on Rails
params.require(:user).permit(:name, :email)
Allows title, body, and published attributes for a post.
Ruby on Rails
params.require(:post).permit(:title, :body, :published)
Allows nested attributes like shipping with address and city inside order.
Ruby on Rails
params.require(:order).permit(:product_id, :quantity, shipping: [:address, :city])
Sample Program

This controller action uses strong parameters to only allow name and email when creating a new user. It prevents any other data from being saved.

Ruby on Rails
class UsersController < ApplicationController
  def create
    user_params = params.require(:user).permit(:name, :email)
    @user = User.new(user_params)
    if @user.save
      render plain: "User created: #{@user.name}, #{@user.email}"
    else
      render plain: "Failed to create user"
    end
  end
end
OutputSuccess
Important Notes

Always use strong parameters in Rails controllers when handling user input.

Without strong parameters, Rails will raise an error to protect your app.

You can permit nested attributes by passing a hash to permit.

Summary

Strong parameters keep your app safe by filtering input data.

Use require and permit to specify allowed data.

This helps prevent security problems like mass assignment.