### Setup and Installation Commands Source: https://github.com/syati/structured_params/blob/main/CONTRIBUTING.md Commands to clone the repository and initialize the development environment including dependencies and git hooks. ```bash git clone https://github.com/Syati/structured_params.git cd structured_params bin/setup ``` -------------------------------- ### Install and Register StructuredParams Source: https://github.com/syati/structured_params/blob/main/README.md Add the gem to your Gemfile and register types in an initializer. ```ruby # Gemfile gem 'structured_params' # config/initializers/structured_params.rb StructuredParams.register_types ``` -------------------------------- ### Install StructuredParams Gem Source: https://github.com/syati/structured_params/blob/main/docs/installation.md Add the gem to your Gemfile or install it directly via the command line. ```ruby gem 'structured_params' ``` ```bash bundle install ``` ```bash gem install structured_params ``` -------------------------------- ### POST /users (ActiveRecord Integration) Source: https://github.com/syati/structured_params/blob/main/docs/serialization.md Example of using StructuredParams to populate ActiveRecord models. ```APIDOC ## POST /users ### Description Creates a new user record using attributes extracted from a StructuredParams object. ### Method POST ### Request Body - **user** (object) - Required - The user parameters object. ### Response #### Success Response (200) - **user** (object) - The created user record. #### Error Response (422) - **errors** (object) - Validation errors from the parameter object. ``` -------------------------------- ### Nested Attribute Translation Examples Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Demonstrates how nested attribute labels are resolved using human_attribute_name. ```ruby UserParameter.human_attribute_name(:'hobbies.0.name') # => "趣味 0 番目の名前" UserParameter.human_attribute_name(:'address.postal_code') # => "住所の郵便番号" ``` -------------------------------- ### Class Name Convention Examples Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Demonstrates how StructuredParams automatically strips suffixes like 'Form' or 'Parameters' from class names to determine model names. ```ruby UserRegistrationForm.model_name.name # => "UserRegistration" UserRegistrationForm.model_name.param_key # => "user_registration" UserParameters.model_name.name # => "User" ``` -------------------------------- ### i18n Translation Configuration Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Example YAML configuration for translating model names, attributes, and error messages in Rails. ```yaml # config/locales/ja.yml ja: activemodel: models: user_registration: "ユーザー登録" attributes: user_registration: name: "名前" email: "メールアドレス" password: "パスワード" password_confirmation: "パスワード(確認)" terms_accepted: "利用規約への同意" errors: models: user_registration: attributes: password_confirmation: confirmation: "パスワードが一致しません" ``` -------------------------------- ### RBS Inline Annotation Style Source: https://github.com/syati/structured_params/blob/main/CONTRIBUTING.md Examples of the required method_type_signature style for RBS annotations in Ruby, including handling of instance variables. ```ruby class Example #: () -> String def method_name "result" end # @rbs @name: String? #: (String) -> void def initialize(name) @name = name end end ``` -------------------------------- ### Initialize Form Objects with Plain Hashes Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Demonstrates initializing form objects with plain hashes, which is useful for controller new actions or testing. ```ruby # Works fine in the new action @form = UserRegistrationForm.new({}) # Works fine in tests form = UserRegistrationForm.new(name: "Alice", email: "alice@example.com") ``` -------------------------------- ### Determine Parameter Keys with permit Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Demonstrates how the permit method automatically resolves the required parameter key based on the model name. ```ruby UserParams.permit(params) # Internally calls: params.require(:user).permit(...) UserRegistrationForm.permit(params) # Internally calls: params.require(:user_registration).permit(...) Admin::UserForm.permit(params) # Internally calls: params.require(:admin_user).permit(...) ``` -------------------------------- ### Instantiate Form Objects and API Parameters Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Use form objects for consistent interfaces with form helpers, or use explicit permit logic for API parameters. ```ruby # Form object - Recommended @form = UserRegistrationForm.new(params) # API with explicit permit - Optional but acceptable user_params = UserParams.new(UserParams.permit(params, require: false)) ``` -------------------------------- ### Instantiate API Parameters Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Use UserParams for automatic filtering and security equivalent to standard Strong Parameters. ```ruby user_params = UserParams.new(params) ``` -------------------------------- ### Testing Against Rails Versions Source: https://github.com/syati/structured_params/blob/main/CONTRIBUTING.md How to test the project against specific Rails versions using environment variables. ```bash RAILS_VERSION="~> 7.2.0" bundle update && bundle exec rspec ``` -------------------------------- ### Implement API Controller with Parameter Objects Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Uses a parameter object to validate and extract attributes for create and update actions in an API context. ```ruby class Api::V1::UsersController < ApplicationController def create user_params = UserParams.new(params) if user_params.valid? user = User.create!(user_params.attributes) render json: user, status: :created else render json: { errors: user_params.errors.to_hash }, status: :unprocessable_entity end end def update user = User.find(params[:id]) user_params = UserParams.new(params) if user_params.valid? && user.update(user_params.attributes) render json: user else render json: { errors: user_params.errors.to_hash }, status: :unprocessable_entity end end end ``` -------------------------------- ### Test and Quality Assurance Commands Source: https://github.com/syati/structured_params/blob/main/CONTRIBUTING.md Standard commands for running the RSpec test suite, RuboCop linting, and Steep type checking. ```bash bundle exec rspec bundle exec rubocop bundle exec steep check ``` -------------------------------- ### Nested Module Namespace Handling Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Shows how namespaces are preserved when form objects are defined within modules. ```ruby module Admin class UserForm < StructuredParams::Params attribute :name, :string end end Admin::UserForm.model_name.name # => "Admin::User" Admin::UserForm.model_name.param_key # => "admin_user" Admin::UserForm.model_name.route_key # => "admin_users" ``` -------------------------------- ### Integrate with ActiveRecord Source: https://github.com/syati/structured_params/blob/main/docs/serialization.md Demonstrates passing attributes directly to ActiveRecord models, including filtering specific fields. ```ruby class UsersController < ApplicationController def create user_params = UserParams.new(params[:user]) if user_params.valid? # Pass all attributes at once user = User.create!(user_params.attributes) # Or exclude specific attributes user = User.new user.assign_attributes(user_params.attributes.except('internal_field')) user.save! render json: user else render json: { errors: user_params.errors }, status: :unprocessable_entity end end end ``` -------------------------------- ### Configure attribute key format Source: https://github.com/syati/structured_params/blob/main/docs/serialization.md Controls whether the returned Hash uses string or symbol keys. ```ruby user_params.attributes # => string keys (default) user_params.attributes(symbolize: true) # => symbol keys ``` -------------------------------- ### Implement Form Objects Source: https://github.com/syati/structured_params/blob/main/README.md Create form objects by inheriting from StructuredParams::Params. Classes ending in 'Form' automatically handle parameter requirement and permitting. ```ruby class UserRegistrationForm < StructuredParams::Params attribute :name, :string attribute :email, :string attribute :terms_accepted, :boolean validates :name, :email, presence: true validates :terms_accepted, acceptance: true end # Use in controller # Passing ActionController::Parameters to a Form class automatically calls # params.require(:user_registration).permit(...) internally. # Use a class name ending with `Form` to enable this behavior. def create form = UserRegistrationForm.new(params) if form.valid? User.create!(form.attributes) redirect_to root_path else render :new end end ``` -------------------------------- ### Manual Control with permit_attribute_names Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Use permit_attribute_names for fine-grained control over permitted parameters in the controller. ```ruby class UsersController < ApplicationController def create permitted_params = params.require(:user).permit(*UserParams.permit_attribute_names) user_params = UserParams.new(permitted_params) if user_params.valid? User.create!(user_params.attributes) else render json: { errors: user_params.errors } end end end ``` -------------------------------- ### Defining a Form Object Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Create a form object by inheriting from StructuredParams::Params and defining attributes and validations. ```ruby class UserRegistrationForm < StructuredParams::Params attribute :name, :string attribute :email, :string attribute :password, :string attribute :password_confirmation, :string attribute :terms_accepted, :boolean validates :name, presence: true, length: { minimum: 2 } validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } validates :password, presence: true, length: { minimum: 8 } validates :password_confirmation, presence: true validates :terms_accepted, acceptance: true validate :passwords_match private def passwords_match return if password == password_confirmation errors.add(:password_confirmation, "doesn't match password") end end ``` -------------------------------- ### Manual Attribute Control Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Use permit_attribute_names to integrate custom fields or maintain backward compatibility with existing Strong Parameters logic. ```ruby permitted = params.require(:user).permit(*UserParams.permit_attribute_names, :custom_field) user_params = UserParams.new(permitted) ``` -------------------------------- ### Formatting Errors for JSON:API Source: https://github.com/syati/structured_params/blob/main/docs/error-handling.md Map validation errors to the JSON:API specification using source pointers. ```ruby def create user_params = UserParams.new(params[:user]) if user_params.valid? # ... success handling else json_api_errors = user_params.errors.to_hash.flat_map do |field, messages| messages.map do |message| { source: { pointer: "/data/attributes/#{field.to_s.gsub('.', '/')}" }, detail: message } end end render json: { errors: json_api_errors }, status: :unprocessable_entity end end ``` -------------------------------- ### Integrate Form Objects with Strong Parameters Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Form objects can handle parameter permitting automatically or via manual control for specific requirements. ```ruby class UsersController < ApplicationController def create # Form classes automatically call require and permit internally @form = UserRegistrationForm.new(params) if @form.valid? user = User.create!(@form.attributes) redirect_to user else render :new end end end ``` ```ruby class UsersController < ApplicationController def create permitted_params = params.require(:user_registration).permit( UserRegistrationForm.permit_attribute_names ) @form = UserRegistrationForm.new(permitted_params) if @form.valid? user = User.create!(@form.attributes) redirect_to user else render :new end end end ``` -------------------------------- ### Integrating Form Objects in Rails Controllers Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Instantiate the form object with params and use its attributes for model creation. Ensure the form object implements permit_attribute_names for parameter filtering. ```ruby class UsersController < ApplicationController def new @form = UserRegistrationForm.new({}) end def create @form = UserRegistrationForm.new(params) if @form.valid? user = User.create!(@form.attributes.except('password_confirmation')) redirect_to user, notice: 'User was successfully created.' else render :new, status: :unprocessable_entity end end end # UserRegistrationForm.new(params) internally resolves: # params.require(:user_registration).permit(UserRegistrationForm.permit_attribute_names) ``` -------------------------------- ### Customizing Nested Attribute Labels Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Configuration for translating nested attribute labels using dot-notation keys in YAML. ```yaml # config/locales/ja.yml ja: activemodel: attributes: user: hobbies: "趣味" address: "住所" hobby: name: "名前" address: postal_code: "郵便番号" errors: nested_attribute: array: "%{parent} %{index} 番目の%{child}" object: "%{parent}の%{child}" ``` -------------------------------- ### Explicit Parameter Permitting Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Allows manual control over parameter permitting when explicit handling is preferred. ```ruby user_params = UserParams.new(UserParams.permit(params, require: false)) ``` -------------------------------- ### Define a basic parameter class Source: https://github.com/syati/structured_params/blob/main/docs/basic-usage.md Inherit from StructuredParams::Params to define attributes and apply ActiveModel validations. ```ruby class UserParams < StructuredParams::Params attribute :name, :string attribute :age, :integer attribute :email, :string validates :name, presence: true validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } end # Usage in controller def create user_params = UserParams.new(params[:user]) if user_params.valid? User.create!(user_params.attributes) else render json: { errors: user_params.errors } end end ``` -------------------------------- ### Automatic Permit List Generation Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Define attributes in a StructuredParams class to automatically generate nested permit structures. ```ruby class UserParams < StructuredParams::Params attribute :name, :string attribute :age, :integer attribute :address, :object, value_class: AddressParams attribute :hobbies, :array, value_class: HobbyParams attribute :tags, :array, value_type: :string end UserParams.permit_attribute_names # => [:name, :age, { address: [:street, :city, :postal_code] }, { hobbies: [:name, :level] }, { tags: [] }] ``` -------------------------------- ### JSON Serialization Source: https://github.com/syati/structured_params/blob/main/docs/serialization.md Methods for converting parameter objects to JSON format. ```APIDOC ## JSON Serialization ### Description Integrates with Rails' JSON serialization to convert parameter objects into JSON strings or serializable Hashes. ### Methods - **to_json**: Returns the object as a JSON string. - **as_json**: Returns the object as a Hash ready for JSON serialization. ``` -------------------------------- ### Define and Use API Parameter Validation Source: https://github.com/syati/structured_params/blob/main/README.md Create parameter classes inheriting from StructuredParams::Params to validate and cast request parameters in controllers. ```ruby class AddressParams < StructuredParams::Params attribute :street, :string attribute :city, :string end class UserParams < StructuredParams::Params attribute :name, :string attribute :age, :integer attribute :score, :integer attribute :tags, :array, value_type: :string # Primitive array attribute :address, :object, value_class: AddressParams # Nested object # validate raw string before type casting validates_raw :score, format: { with: /\A\d+\z/, message: 'must be numeric string' } validates :name, presence: true validates :age, numericality: { greater_than: 0 } validates :score, numericality: { greater_than_or_equal_to: 0 } end # Use in API controller def create user_params = UserParams.new(params) if user_params.valid? User.create!(user_params.attributes) else render json: { errors: user_params.errors }, status: :unprocessable_entity end end ``` -------------------------------- ### Configure StructuredParams Source: https://github.com/syati/structured_params/blob/main/docs/installation.md Customize gem behavior, such as the array index base for error messages, within the initializer. ```ruby # config/initializers/structured_params.rb StructuredParams.register_types StructuredParams.configure do |config| # Controls how array indices appear in human attribute names and full_messages. # 0 (default) — 0-based: "Hobbies 0 Name can't be blank" # 1 — 1-based: "Hobbies 1 Name can't be blank" config.array_index_base = 1 end ``` -------------------------------- ### Accessing Basic Error Information Source: https://github.com/syati/structured_params/blob/main/docs/error-handling.md Retrieve validation errors in a flat structure using dot notation or generate full error messages. ```ruby user_params = UserParams.new(invalid_params) user_params.valid? # => false # Standard error access (flat structure with dot notation) user_params.errors.to_hash # => { :name => ["can't be blank"], :'address.postal_code' => ["can't be blank"] } # Full error messages user_params.errors.full_messages # => ["Name can't be blank", "Address postal code can't be blank"] ``` -------------------------------- ### Implement a Save Method in Form Objects Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Encapsulates persistence logic within the form object to simplify controller actions. ```ruby class UserRegistrationForm < StructuredParams::Params attribute :name, :string attribute :email, :string attribute :password, :string validates :name, :email, :password, presence: true def save return false unless valid? User.create!(attributes.except('password_confirmation')) end end # Controller def create @form = UserRegistrationForm.new(user_params) if @form.save redirect_to root_path, notice: 'Successfully registered!' else render :new end end ``` -------------------------------- ### RBS Type Signature Generation Source: https://github.com/syati/structured_params/blob/main/CONTRIBUTING.md Methods for generating RBS signatures, including manual execution and git hook configuration. ```bash bundle exec rbs-inline --output=sig lib/**/*.rb ``` ```yaml prepare-commit-msg: commands: rbs-inline: run: bundle exec rbs-inline --output=sig lib/**/*.rb ``` -------------------------------- ### Combine validates_raw and validates Source: https://github.com/syati/structured_params/blob/main/docs/validation.md Apply both raw and standard validations to the same attribute to aggregate error messages. ```ruby class UserParams < StructuredParams::Params attribute :score, :integer validates_raw :score, format: { with: /\A\d+\z/, message: 'must be numeric string' } validates :score, numericality: { greater_than_or_equal_to: 0 } end params = UserParams.new(score: 'abc') params.valid? # => false params.errors[:score] # => includes errors from both validates_raw and validates ``` -------------------------------- ### Implement Basic Validations in StructuredParams Source: https://github.com/syati/structured_params/blob/main/docs/validation.md Define standard ActiveModel validations and custom validation methods within a StructuredParams class. ```ruby class UserParams < StructuredParams::Params attribute :name, :string attribute :age, :integer attribute :email, :string attribute :address, :object, value_class: AddressParams validates :name, presence: true, length: { minimum: 2 } validates :age, presence: true, numericality: { greater_than: 0 } validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } validates :address, presence: true validate :custom_validation private def custom_validation errors.add(:age, "must be adult") if age && age < 18 end end ``` -------------------------------- ### Use Transactions in Save Methods Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Wraps multiple model creations in a transaction to ensure data integrity during the save process. ```ruby def save return false unless valid? ActiveRecord::Base.transaction do user = User.create!(name: name, email: email) Profile.create!(bio: bio, user: user) end true rescue ActiveRecord::RecordInvalid false end ``` -------------------------------- ### Define Primitive Arrays Source: https://github.com/syati/structured_params/blob/main/README.md Use the value_type option to define primitive arrays, which automatically generates the appropriate Strong Parameters permit list. ```ruby class UserParams < StructuredParams::Params attribute :tags, :array, value_type: :string end # Equivalent Strong Parameters: # params.permit(tags: []) ``` -------------------------------- ### Apply Conditional Validations Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Defines validations that trigger only when specific conditions are met, such as checking for a password change. ```ruby class UserUpdateForm < StructuredParams::Params attribute :name, :string attribute :email, :string attribute :password, :string attribute :current_password, :string validates :name, :email, presence: true validates :current_password, presence: true, if: :password_change? validates :password, length: { minimum: 8 }, if: :password_change? private def password_change? password.present? end end ``` -------------------------------- ### attributes Method Source: https://github.com/syati/structured_params/blob/main/docs/serialization.md Retrieves all attributes of a parameter object as a nested Hash. ```APIDOC ## attributes Method ### Description Returns all attributes of the parameter object as a nested Hash. Nested objects are serialized recursively. ### Parameters #### Options - **symbolize** (boolean) - Optional - If true, returns keys as symbols instead of strings. ``` -------------------------------- ### Test Form Objects with RSpec Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Validate form logic and persistence behavior using standard RSpec unit tests. ```ruby RSpec.describe UserRegistrationForm do describe 'validations' do it 'is valid with valid attributes' do form = UserRegistrationForm.new( name: 'John Doe', email: 'john@example.com', password: 'password123', password_confirmation: 'password123', terms_accepted: true ) expect(form).to be_valid end it 'is invalid without a name' do form = UserRegistrationForm.new(name: '') expect(form).not_to be_valid expect(form.errors[:name]).to be_present end it 'is invalid with a short password' do form = UserRegistrationForm.new(password: 'short') expect(form).not_to be_valid expect(form.errors[:password]).to be_present end end describe '#save' do it 'creates a user when valid' do form = UserRegistrationForm.new(valid_attributes) expect { form.save }.to change(User, :count).by(1) end end end ``` -------------------------------- ### Generating Structured Error Formats Source: https://github.com/syati/structured_params/blob/main/docs/error-handling.md Return errors as a nested hash structure, optionally including full error messages for frontend integration. ```ruby # Get errors in structured format (symbol keys) user_params.errors.to_hash(false, structured: true) # => { # :name => ["can't be blank"], # :address => { :postal_code => ["can't be blank"] }, # :hobbies => { :'0' => { :name => ["can't be blank"] } } # } # With full error messages user_params.errors.to_hash(true, structured: true) # => { # :name => ["Name can't be blank"], # :address => { :postal_code => ["Address postal code can't be blank"] } # } ``` -------------------------------- ### API Controller Integration Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Uses UserParams to automatically extract and validate attributes from controller parameters. ```ruby class Api::V1::UsersController < ApplicationController def create user_params = UserParams.new(params) if user_params.valid? user = User.create!(user_params.attributes) render json: user, status: :created else render json: { errors: user_params.errors.to_hash }, status: :unprocessable_entity end end end ``` -------------------------------- ### Integrate Form Objects in API Controllers Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Use form objects to validate incoming API parameters before persisting data. ```ruby class Api::V1::UsersController < Api::V1::BaseController def create @form = UserRegistrationForm.new(params) if @form.valid? user = User.create!(@form.attributes) render json: user, status: :created else render json: { errors: @form.errors }, status: :unprocessable_entity end end end ``` -------------------------------- ### Retrieve attributes as a Hash Source: https://github.com/syati/structured_params/blob/main/docs/serialization.md Returns all attributes as a nested Hash. Nested objects are processed recursively. ```ruby user_params = UserParams.new({ name: "John Doe", address: { street: "123 Main St", city: "New York" }, hobbies: [ { name: "Photography", level: "beginner" }, { name: "Cooking", level: "intermediate" } ] }) user_params.attributes # => { # "name" => "John Doe", # "address" => { "street" => "123 Main St", "city" => "New York" }, # "hobbies" => [ # { "name" => "Photography", "level" => "beginner" }, # { "name" => "Cooking", "level" => "intermediate" } # ] # } ``` -------------------------------- ### Define nested objects Source: https://github.com/syati/structured_params/blob/main/docs/basic-usage.md Use the :object type with a value_class to nest parameter definitions. ```ruby class AddressParams < StructuredParams::Params attribute :street, :string attribute :city, :string attribute :postal_code, :string end class UserParams < StructuredParams::Params attribute :name, :string attribute :address, :object, value_class: AddressParams end # Usage params = { name: "John Doe", address: { street: "123 Main St", city: "New York", postal_code: "10001" } } user_params = UserParams.new(params) user_params.address # => AddressParams instance user_params.address.city # => "New York" ``` -------------------------------- ### Implementing Flat Error Responses in Controllers Source: https://github.com/syati/structured_params/blob/main/docs/error-handling.md Render the structured error hash directly within a Rails controller response. ```ruby class UsersController < ApplicationController def create user_params = UserParams.new(params[:user]) if user_params.valid? User.create!(user_params.attributes) render json: { success: true } else render json: { errors: user_params.errors.to_hash(false, structured: true), success: false }, status: :unprocessable_entity end end end ``` -------------------------------- ### Validate Raw Input with validates_raw Source: https://github.com/syati/structured_params/blob/main/docs/validation.md Use validates_raw to enforce format constraints on input values before they undergo type casting. ```ruby class UserParams < StructuredParams::Params attribute :age, :integer validates_raw :age, format: { with: /\A\d+\z/, message: 'must be numeric string' } end params = UserParams.new(age: '12x') params.valid? # => false params.errors.to_hash # => { age: ["must be numeric string"] } ``` -------------------------------- ### Displaying Translated Model Names in Views Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Usage of model_name.human within a Rails form_with helper to display translated labels. ```erb <%= form_with model: @form, url: users_path do |f| %>

<%= @form.model_name.human %>

<%= f.label :name %> <%= f.text_field :name %> <%= f.label :email %> <%= f.email_field :email %> <% end %> ``` -------------------------------- ### Binding Form Objects to Rails Views Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Use form_with to bind the form object to the view, enabling automatic error handling and field population. ```erb <%= form_with model: @form, url: users_path do |f| %> <% if @form.errors.any? %>

<%= pluralize(@form.errors.count, "error") %> prohibited this registration:

<% end %>
<%= f.label :name %> <%= f.text_field :name %>
<%= f.label :email %> <%= f.email_field :email %>
<%= f.label :password %> <%= f.password_field :password %>
<%= f.label :password_confirmation %> <%= f.password_field :password_confirmation %>
<%= f.check_box :terms_accepted %> <%= f.label :terms_accepted, "I accept the terms and conditions" %>
<%= f.submit "Sign up" %>
<% end %> ``` -------------------------------- ### Serialize to JSON Source: https://github.com/syati/structured_params/blob/main/docs/serialization.md Utilizes Rails' JSON serialization methods for parameter objects. ```ruby user_params.to_json # => JSON string user_params.as_json # => Hash ready for JSON serialization ``` -------------------------------- ### Combine multiple models in a form Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Handle multiple models within a single form object by defining nested attributes and implementing a custom save method. ```ruby class UserProfileForm < StructuredParams::Params attribute :user_name, :string attribute :user_email, :string attribute :profile, :object, value_class: ProfileAttributes validates :user_name, presence: true validates :user_email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } def save return false unless valid? ActiveRecord::Base.transaction do user = User.create!(name: user_name, email: user_email) Profile.create!(profile.attributes.merge(user: user)) end true end end class ProfileAttributes < StructuredParams::Params attribute :bio, :string attribute :website, :string attribute :location, :string validates :website, format: { with: URI::DEFAULT_PARSER.make_regexp }, allow_blank: true end ``` -------------------------------- ### Register Custom Type Names Source: https://github.com/syati/structured_params/blob/main/docs/installation.md Use custom names for types to prevent naming collisions with existing ActiveModel types. ```ruby StructuredParams.register_types_as( object_name: :structured_object, array_name: :structured_array ) # Then use in your parameter classes class UserParams < StructuredParams::Params attribute :address, :structured_object, value_class: AddressParams attribute :hobbies, :structured_array, value_class: HobbyParams end ``` -------------------------------- ### Configure Nested Validations Source: https://github.com/syati/structured_params/blob/main/docs/validation.md Define nested structures using value_class to enable automatic cascading validation for objects and arrays. ```ruby class AddressParams < StructuredParams::Params attribute :street, :string attribute :city, :string attribute :postal_code, :string validates :street, presence: true validates :city, presence: true validates :postal_code, presence: true, format: { with: /\A\d{5}\z/ } end class HobbyParams < StructuredParams::Params attribute :name, :string attribute :level, :string validates :name, presence: true validates :level, inclusion: { in: %w[beginner intermediate advanced] } end class UserParams < StructuredParams::Params attribute :name, :string attribute :address, :object, value_class: AddressParams attribute :hobbies, :array, value_class: HobbyParams validates :name, presence: true validates :address, presence: true end ``` -------------------------------- ### Define arrays of nested objects Source: https://github.com/syati/structured_params/blob/main/docs/basic-usage.md Use the :array type with value_class to define collections of structured objects. ```ruby class HobbyParams < StructuredParams::Params attribute :name, :string attribute :level, :string end class UserParams < StructuredParams::Params attribute :name, :string attribute :hobbies, :array, value_class: HobbyParams end # Usage params = { name: "Alice", hobbies: [ { name: "Photography", level: "beginner" }, { name: "Cooking", level: "intermediate" } ] } user_params = UserParams.new(params) user_params.hobbies # => [HobbyParams, HobbyParams] user_params.hobbies.first.name # => "Photography" ``` -------------------------------- ### Pass params to Form Objects Source: https://github.com/syati/structured_params/blob/main/docs/strong-parameters.md Pass params directly to a form object to automatically resolve nested parameter keys. ```ruby class UsersController < ApplicationController def create @form = UserRegistrationForm.new(params) if @form.valid? user = User.create!(@form.attributes) redirect_to user, notice: 'User was successfully created.' else render :new, status: :unprocessable_entity end end end ``` -------------------------------- ### Separate validation from models Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Use a form object to encapsulate form-specific validations while keeping the persistence model focused on database operations. ```ruby # Model focuses on persistence class User < ApplicationRecord has_secure_password end # Form object handles form-specific validations class UserRegistrationForm < StructuredParams::Params attribute :name, :string attribute :email, :string attribute :password, :string attribute :password_confirmation, :string validates :password_confirmation, presence: true validate :passwords_match end ``` -------------------------------- ### Define arrays of primitive types Source: https://github.com/syati/structured_params/blob/main/docs/basic-usage.md Use the :array type with value_type to define collections of scalar values. ```ruby class UserParams < StructuredParams::Params attribute :tags, :array, value_type: :string attribute :scores, :array, value_type: :integer end # Usage params = { tags: ["ruby", "rails", "programming"], scores: [85, 92, 78] } user_params = UserParams.new(params) user_params.tags # => ["ruby", "rails", "programming"] user_params.scores # => [85, 92, 78] ``` -------------------------------- ### Register StructuredParams Types Source: https://github.com/syati/structured_params/blob/main/docs/installation.md Explicitly register the :object and :array types in a Rails initializer to enable ActiveModel type lookup. ```ruby # config/initializers/structured_params.rb StructuredParams.register_types ``` -------------------------------- ### Transforming Error Key Formats Source: https://github.com/syati/structured_params/blob/main/docs/error-handling.md Use standard Ruby methods to modify error keys for specific output requirements like JSON Pointers or custom prefixes. ```ruby # JSON Pointer format user_params.errors.to_hash.transform_keys { |key| "/#{key.to_s.gsub('.', '/')}" } # => { "/name" => ["can't be blank"], "/address/postal_code" => ["can't be blank"] } # Uppercase format user_params.errors.to_hash.transform_keys(&:upcase) # => { "NAME" => ["can't be blank"], "ADDRESS.POSTAL_CODE" => ["can't be blank"] } # Custom prefix user_params.errors.to_hash.transform_keys { |key| "field_#{key}" } # => { "field_name" => ["can't be blank"], "field_address.postal_code" => ["can't be blank"] } ``` -------------------------------- ### Define nested forms Source: https://github.com/syati/structured_params/blob/main/docs/form-objects.md Use the :object type to define nested form structures with their own validation rules. ```ruby class OrderForm < StructuredParams::Params attribute :product_name, :string attribute :quantity, :integer attribute :shipping_address, :object, value_class: AddressForm attribute :billing_address, :object, value_class: AddressForm validates :product_name, presence: true validates :quantity, numericality: { greater_than: 0 } end class AddressForm < StructuredParams::Params attribute :street, :string attribute :city, :string attribute :postal_code, :string attribute :country, :string validates :street, :city, :postal_code, :country, presence: true end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.