0
0
RailsHow-ToBeginner · 3 min read

How to Use Strong Parameters in Ruby on Rails

In Ruby on Rails, use strong parameters by defining a private method that calls params.require(:model).permit(:attribute1, :attribute2) inside your controller. This ensures only allowed attributes are accepted from user input, protecting your app from unwanted data changes.
📐

Syntax

The basic syntax for strong parameters involves calling require to specify the expected parameter key, then permit to list allowed attributes.

  • params.require(:model): Ensures the parameter for the model is present.
  • .permit(:attr1, :attr2): Allows only these attributes to be accepted.
ruby
def model_params
  params.require(:model).permit(:attribute1, :attribute2)
end
💻

Example

This example shows a Rails controller using strong parameters to safely create a new Article with only title and content allowed from user input.

ruby
class ArticlesController < ApplicationController
  def create
    @article = Article.new(article_params)
    if @article.save
      render json: { message: 'Article created successfully' }, status: :created
    else
      render json: { errors: @article.errors.full_messages }, status: :unprocessable_entity
    end
  end

  private

  def article_params
    params.require(:article).permit(:title, :content)
  end
end
Output
{"message":"Article created successfully"} (if valid input)
⚠️

Common Pitfalls

Common mistakes include:

  • Not using require, which can cause errors if the expected parameter is missing.
  • Permitting attributes that should not be changed by users, risking security issues.
  • Forgetting to make the strong parameters method private, exposing it unintentionally.
ruby
class UsersController < ApplicationController
  # Wrong: permits all params without require
  def user_params_wrong
    params.permit(:name, :admin)
  end

  # Right: requires user key and permits safe attributes only
  private
  def user_params_right
    params.require(:user).permit(:name)
  end
end
📊

Quick Reference

  • Use params.require(:model) to ensure the parameter exists.
  • Use .permit(:attr1, :attr2) to whitelist allowed attributes.
  • Keep the strong parameters method private in your controller.
  • Never permit sensitive attributes like admin or password_digest directly.

Key Takeaways

Always use strong parameters to whitelist allowed attributes in Rails controllers.
Call params.require(:model) before permit to ensure the parameter is present.
Keep your strong parameters method private to avoid exposing it.
Never permit sensitive or admin-only attributes from user input.
Strong parameters protect your app from mass assignment security risks.