Rails strong parameters for nested attributes

Maya Patel Jan 2026
1 tab
module Api
  module V1
    class PostsController < ApplicationController
      def create
        post = current_user.posts.build(post_params)

        if post.save
          render json: post, serializer: PostSerializer, 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, serializer: PostSerializer
        else
          render json: { errors: post.errors }, status: :unprocessable_entity
        end
      end

      private

      def post_params
        params.require(:post).permit(
          :title,
          :body,
          :status,
          :cover_image_blob_id,
          tags: [],
          images_attributes: [:id, :blob_id, :caption, :_destroy],
          meta_attributes: [:description, :keywords, :og_image]
        )
      end
    end
  end
end
1 file · ruby Explain with highlit

Strong parameters prevent mass assignment vulnerabilities by explicitly permitting allowed attributes. For nested associations like a post with embedded images or comments, I use nested permit calls. Arrays of primitives use [] syntax, while hashes of attributes use nested hashes. The _destroy parameter enables deletion of associated records through forms. I create private permit methods for complex nested structures to keep controllers clean. Strong parameters work seamlessly with React forms that post JSON—Rails parses the JSON into params automatically. Validation errors for nested attributes surface correctly in API responses. This security layer is essential for any Rails API accepting user input.