ruby 33 lines · 1 tab

Strong parameters for mass assignment protection

Alex Kumar Jan 2026
1 tab
module Api
  module V1
    class PostsController < BaseController
      before_action :authenticate_user!

      def create
        post = current_user.posts.build(post_params)

        if post.save
          render json: post, status: :created
        else
          render json: { errors: post.errors }, status: :unprocessable_entity
        end
      end

      def update
        post = current_user.posts.find(params[:id])

        if post.update(post_params)
          render json: post, status: :ok
        else
          render json: { errors: post.errors }, status: :unprocessable_entity
        end
      end

      private

      def post_params
        params.require(:post).permit(:title, :body, :published_at, tags: [])
      end
    end
  end
end
1 file · ruby Explain with highlit

Strong parameters prevent mass assignment vulnerabilities by explicitly whitelisting which attributes can be set via user input. Without this protection, attackers could modify sensitive fields like admin or account_balance by including them in request payloads. I define private *_params methods in controllers that specify exactly which parameters are permitted for each action. Nested attributes require nested permit calls, which can get verbose but ensures nothing slips through. For APIs, I often see developers disable strong parameters entirely, which is dangerous—instead, I keep them enabled and use schemas (like dry-validation or JSON Schema) as an additional validation layer. Strong parameters are the first line of defense against unauthorized data modification.


Related snips

Share this code

Here's the card — post it anywhere.

Strong parameters for mass assignment protection — share card
Link copied