[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FAKX109C63VJJ2XCVNFB1G":3,"skill-same:01M7FAKX109C63VJJ2XCVNFB1G":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7FAKX109C63VJJ2XCVNFB1G","rails-patterns",null,"Ruby on Rails framework patterns for Rails 7.1+ and 8.x apps. Covers the directory contract, skinny controllers with service objects, form objects, query objects, idiomatic ActiveRecord, background jobs, ViewComponent, Hotwire, and the Rails 8 Solid stack. Use when building or reviewing Rails apps, controllers, models, services, jobs, or views.","siddu1004\u002FSFP","siddu1004","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F260113491?v=4","01M7F8W1SAJAR49097VRTE1TW5","Siddhardh Vanguri","01M7F8W1SYGY7JE15AHAECCT9R",5,"MIT","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fbackend\u002Fskills\u002Frails-patterns\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: rails-patterns\ndescription: Ruby on Rails framework patterns for Rails 7.1+ and 8.x apps. Covers the directory contract, skinny controllers with service objects, form objects, query objects, idiomatic ActiveRecord, background jobs, ViewComponent, Hotwire, and the Rails 8 Solid stack. Use when building or reviewing Rails apps, controllers, models, services, jobs, or views.\norigin: community\n---\n\n# Rails Patterns\n\nFramework patterns for modern Ruby on Rails applications (Rails 7.1+ and 8.x). Rails is opinionated by design; these are the patterns the community has converged on for apps that stay maintainable past the 50-model mark. This skill is the \"how.\" For the \"what\" and \"when\" (the decisions about which pattern to reach for), see the Ruby patterns rules — `rules\u002Fruby\u002Fpatterns.md` in this repository, installed as `rules\u002Fecc\u002Fruby\u002Fpatterns.md`.\n\n## When to Activate\n\n- Building a Rails application (full-stack, API-only, or hybrid)\n- Reviewing a PR that touches `app\u002F` or `config\u002F`\n- Generating models, controllers, services, or jobs\n- A controller action grows past ~10 lines\n- A model file grows past ~200 lines\n- ActiveRecord queries start appearing in controllers or views\n\n## Core Concepts\n\n### The directory contract\n\nRails apps follow a predictable structure. Add directories deliberately, not casually.\n\n```\napp\u002F\n  models\u002F         ActiveRecord models. Persistence and domain logic close to the data.\n  controllers\u002F    HTTP request handling. Thin orchestration only.\n  views\u002F          ERB templates. No business logic.\n  components\u002F     ViewComponent classes. View logic that needs tests.\n  services\u002F       Service objects. Multi-step business operations.\n  forms\u002F          Form objects. Complex form handling across multiple models.\n  queries\u002F        Query objects. Reusable, composable ActiveRecord queries.\n  jobs\u002F           Background jobs. Async work via Solid Queue, Sidekiq, or GoodJob.\n  mailers\u002F        ActionMailer classes.\n  helpers\u002F        View helpers. Tiny presentational logic only.\n  policies\u002F       Authorization policies (if using Pundit). Optional.\n  channels\u002F       ActionCable channels for WebSocket work.\n```\n\nAvoid `app\u002Flib\u002F`, `app\u002Futils\u002F`, `app\u002Fmanagers\u002F`. If something does not fit the directories above, the design usually needs rethinking, not a new directory. Truly generic code goes in `lib\u002F`.\n\n### Skinny controllers\n\nControllers receive a request, delegate to the right object, and render a response. Business logic lives elsewhere. (Per the Ruby patterns rules, extract to a service object when the controller starts carrying multiple responsibilities.)\n\n### Service objects\n\nThe default for business operations that touch more than a single model save. Conventions that keep them consistent:\n\n- Namespace by domain (`Invoices::Create`), not by suffix (`InvoiceCreator`).\n- A class method `.call` delegates to an instance `#call`.\n- Return a Result object, not a boolean or a bare record, so the caller can branch on success, errors, and the affected record.\n- Wrap multi-record writes in a transaction.\n- Keep each service single-purpose (`Invoices::Create`, `Invoices::MarkPaid`), never `Invoices::Manager`.\n\n### Form objects\n\nWhen a form spans multiple models or has fields that do not map to columns, use a form object rather than nested attributes or virtual attributes on the wrong model. It quacks like a model to the view (`form_with model: @form`) while composing records cleanly.\n\n### Query objects\n\nFor ActiveRecord queries reused across controllers or services, or too complex for a scope, extract a query object that accepts a scope as input so it composes. Rule of thumb: a scope that grows past three chained conditions or starts taking parameters wants to be a query object.\n\n### Background jobs\n\nOffload anything slow. (Per the Ruby patterns rules, Solid Queue for greenfield Rails 8 with modest throughput; Sidekiq when you need mature observability, high throughput, or existing Redis.) Regardless of adapter: pass IDs not records, make `perform` idempotent, and set `retry_on`\u002F`discard_on` explicitly.\n\n### ViewComponent over partials\n\nFor view logic with conditional rendering, more than two arguments, or reuse across more than three places, prefer a ViewComponent. Components are testable in isolation and surface their interface explicitly; partials with deep conditional logic become debt.\n\n### Hotwire: Turbo and Stimulus\n\nThe default Rails frontend stack. (Per the Ruby patterns rules, prefer Hotwire for server-rendered apps; reach for React\u002FVue only when interaction complexity justifies the client surface.) Turbo Frames for partial page updates, Turbo Streams for server-driven updates, Stimulus for small client-side behaviors next to the markup.\n\n### The Rails 8 Solid stack\n\nRails 8 ships database-backed defaults that previously needed Redis: Solid Queue (jobs), Solid Cache (cache), Solid Cable (ActionCable). The tradeoff is more database load for one fewer infrastructure component; a good fit for modest throughput, with Redis still winning at high scale. Kamal is the default Docker-based deploy tool.\n\n## Code Examples\n\n### Skinny controller with a service object\n\n```ruby\n# Bad: business logic in the controller\nclass InvoicesController \u003C ApplicationController\n  def create\n    @invoice = Invoice.new(invoice_params)\n    @invoice.user = current_user\n    @invoice.line_items.build(invoice_params[:line_items])\n    @invoice.tax_total = TaxCalculator.new(@invoice).calculate\n    @invoice.total = @invoice.line_items.sum(&:amount) + @invoice.tax_total\n\n    if @invoice.save\n      InvoiceMailer.created(@invoice).deliver_later\n      AccountingExportJob.perform_later(@invoice.id)\n      redirect_to @invoice, notice: \"Invoice created\"\n    else\n      render :new\n    end\n  end\nend\n\n# Good: controller orchestrates, service does the work\nclass InvoicesController \u003C ApplicationController\n  def create\n    result = Invoices::Create.call(params: invoice_params, user: current_user)\n\n    if result.success?\n      redirect_to result.invoice, notice: \"Invoice created\"\n    else\n      @invoice = result.invoice\n      render :new, status: :unprocessable_entity\n    end\n  end\nend\n```\n\n### The service object\n\n```ruby\n# app\u002Fservices\u002Finvoices\u002Fcreate.rb\nmodule Invoices\n  class Create\n    # Struct keeps this runnable on every Ruby that Rails 7.1 supports.\n    # On Ruby 3.2+, `Data.define(:success?, :invoice, :errors)` is a more\n    # concise immutable alternative.\n    Result = Struct.new(:success, :invoice, :errors, keyword_init: true) do\n      def success?\n        success\n      end\n    end\n\n    def self.call(params:, user:)\n      new(params: params, user: user).call\n    end\n\n    def initialize(params:, user:)\n      @params = params\n      @user = user\n    end\n\n    def call\n      invoice = build_invoice\n      ApplicationRecord.transaction do\n        invoice.save!\n      end\n      begin\n        send_notifications(invoice)\n      rescue StandardError => e\n        Rails.logger.error(\"Notification dispatch failed for invoice #{invoice.id}: #{e.message}\")\n      end\n      Result.new(success: true, invoice: invoice, errors: nil)\n    rescue ActiveRecord::RecordInvalid => e\n      Result.new(success: false, invoice: e.record, errors: e.record.errors)\n    end\n\n    private\n\n    attr_reader :params, :user\n\n    def build_invoice\n      invoice = user.invoices.new(params.except(:line_items))\n      invoice.line_items.build(params[:line_items])\n      invoice.tax_total = TaxCalculator.call(invoice)\n      invoice.total = invoice.line_items.sum(&:amount) + invoice.tax_total\n      invoice\n    end\n\n    def send_notifications(invoice)\n      InvoiceMailer.created(invoice).deliver_later\n      AccountingExportJob.perform_later(invoice.id)\n    end\n  end\nend\n```\n\n### Form object\n\n```ruby\n# app\u002Fforms\u002Fsignup_form.rb\nclass SignupForm\n  include ActiveModel::Model\n  include ActiveModel::Attributes\n\n  attribute :email, :string\n  attribute :password, :string\n  attribute :company_name, :string\n  attribute :terms_accepted, :boolean\n\n  validates :email, presence: true, format: URI::MailTo::EMAIL_REGEXP\n  validates :password, presence: true, length: { minimum: 12 }\n  validates :company_name, presence: true\n  validates :terms_accepted, acceptance: true\n\n  attr_reader :user, :company\n\n  def save\n    return false unless valid?\n\n    ApplicationRecord.transaction do\n      @company = Company.create!(name: company_name)\n      @user = @company.users.create!(email: email, password: password, role: :owner)\n    end\n    true\n  rescue ActiveRecord::RecordInvalid => e\n    errors.merge!(e.record.errors)\n    false\n  end\nend\n```\n\n### Query object\n\n```ruby\n# app\u002Fqueries\u002Finvoices\u002Foverdue.rb\nmodule Invoices\n  class Overdue\n    def self.call(scope: Invoice.all, as_of: Time.current)\n      new(scope: scope, as_of: as_of).call\n    end\n\n    def initialize(scope:, as_of:)\n      @scope = scope\n      @as_of = as_of\n    end\n\n    def call\n      scope\n        .where(status: :sent)\n        .where(due_date: ..as_of)\n        .where.not(id: paid_invoice_ids)\n        .includes(:customer, :line_items)\n    end\n\n    private\n\n    attr_reader :scope, :as_of\n\n    def paid_invoice_ids\n      Payment.where(created_at: ..as_of).pluck(:invoice_id)\n    end\n  end\nend\n```\n\nQuery objects accept a scope, so they compose: `Invoices::Overdue.call(scope: current_user.invoices)`.\n\n### N+1 prevention\n\n```ruby\n# Bad: N+1 in the view when it calls post.author.name\n@posts = Post.published\n\n# Good: eager load\n@posts = Post.published.includes(:author)\n```\n\n`includes` lets Rails choose preload vs eager_load. Force `preload` for separate queries, `eager_load` for a JOIN when filtering on the association. Since Rails 6.1, `strict_loading` raises on accidental lazy loads.\n\n### Counter cache\n\n```ruby\nclass Comment \u003C ApplicationRecord\n  belongs_to :post, counter_cache: true\nend\n```\n\n```ruby\nadd_column :posts, :comments_count, :integer, default: 0, null: false\n```\n\n`post.comments_count` becomes a column read instead of a `COUNT(*)`. This example\nassumes a new table; adding a counter cache to a table that already has rows requires a\nbackfill, which is out of scope here.\n\n### Background job shape\n\nPass record IDs, not records. Retries make delivery at-least-once, so any job that calls\nan external service must be idempotent — otherwise a transient failure after the remote\ncall succeeds will duplicate the effect on the next attempt.\n\n```ruby\nclass AccountingExportJob \u003C ApplicationJob\n  queue_as :exports\n\n  retry_on AccountingApi::TransientError, wait: :polynomially_longer, attempts: 5\n  discard_on AccountingApi::PermanentError\n\n  def perform(invoice_id)\n    invoice = Invoice.find(invoice_id)\n    export = AccountingExport.create_or_find_by!(\n      invoice: invoice,\n      idempotency_key: \"invoice-export-#{invoice.id}-#{invoice.updated_at.to_i}\"\n    )\n    return if export.completed_at?\n\n    receipt = AccountingApi.export(invoice, idempotency_key: export.idempotency_key)\n    export.update!(completed_at: Time.current, external_id: receipt.id)\n  end\nend\n```\n\n```ruby\nadd_index :accounting_exports, :idempotency_key, unique: true\n```\n\nThe unique index is what makes this safe: when two attempts race, the database rejects\nthe second insert and Active Record resolves the conflict inside the call, returning the\nexisting row. That happens without any job-level retry — `retry_on` above covers only\n`AccountingApi::TransientError`. The guard\ncovers the window before the remote call; passing `idempotency_key` through to the API\ncovers the window after it, so a crash between the API call and `update!` still resolves\nto a single export.\n\n### ViewComponent\n\n```ruby\n# app\u002Fcomponents\u002Finvoice_status_badge_component.rb\nclass InvoiceStatusBadgeComponent \u003C ViewComponent::Base\n  STATUS_CLASSES = {\n    draft: \"bg-gray-100 text-gray-800\",\n    sent: \"bg-blue-100 text-blue-800\",\n    paid: \"bg-green-100 text-green-800\",\n    overdue: \"bg-red-100 text-red-800\"\n  }.freeze\n\n  def initialize(invoice:)\n    @invoice = invoice\n  end\n\n  def call\n    tag.span(@invoice.status.humanize, class: \"rounded-full px-2 py-1 text-sm #{status_class}\")\n  end\n\n  private\n\n  def status_class\n    STATUS_CLASSES.fetch(@invoice.status.to_sym, \"bg-gray-100\")\n  end\nend\n```\n\n```erb\n\u003C%= render InvoiceStatusBadgeComponent.new(invoice: @invoice) %>\n```\n\n### Hotwire\n\n```erb\n\u003C%# Turbo Frame: clicking Edit replaces only this frame %>\n\u003C%= turbo_frame_tag \"invoice_#{@invoice.id}\" do %>\n  \u003Cdiv class=\"invoice\">\n    \u003C%= link_to \"Edit\", edit_invoice_path(@invoice) %>\n  \u003C\u002Fdiv>\n\u003C% end %>\n```\n\n```erb\n\u003C%# Turbo Stream: app\u002Fviews\u002Fcomments\u002Fcreate.turbo_stream.erb %>\n\u003C%= turbo_stream.append \"comments\", @comment %>\n\u003C%= turbo_stream.update \"comment_form\", partial: \"form\", locals: { comment: Comment.new } %>\n```\n\n```javascript\n\u002F\u002F app\u002Fjavascript\u002Fcontrollers\u002Fcopy_to_clipboard_controller.js\nimport { Controller } from \"@hotwired\u002Fstimulus\"\n\nexport default class extends Controller {\n  static targets = [\"source\"]\n\n  copy() {\n    navigator.clipboard.writeText(this.sourceTarget.value)\n  }\n}\n```\n\n### Acceptable vs unacceptable callbacks\n\n```ruby\n# Acceptable: pure data normalization\nclass User \u003C ApplicationRecord\n  before_validation :normalize_email\n\n  private\n\n  def normalize_email\n    self.email = email.to_s.downcase.strip\n  end\nend\n\n# Move to a service instead: side effects hidden in a callback\n# class User \u003C ApplicationRecord\n#   after_create :send_welcome_email  # hard to opt out of, hard to test\n# end\n```\n\n### Good concern vs bad concern\n\n```ruby\n# Good: genuinely cross-cutting, reusable across unrelated models\n# app\u002Fmodels\u002Fconcerns\u002Fsoft_deletable.rb\nmodule SoftDeletable\n  extend ActiveSupport::Concern\n\n  included do\n    scope :active, -> { where(deleted_at: nil) }\n    scope :deleted, -> { where.not(deleted_at: nil) }\n  end\n\n  def soft_delete! = update!(deleted_at: Time.current)\n  def restore! = update!(deleted_at: nil)\nend\n\n# Bad: a \"concern\" used by exactly one model, holding logic that belongs on it\n# app\u002Fmodels\u002Fconcerns\u002Finvoice_calculations.rb\nmodule InvoiceCalculations\n  extend ActiveSupport::Concern\n\n  def calculate_total\n    line_items.sum(&:amount) + tax_total\n  end\nend\n# Only Invoice includes this. It isn't cross-cutting; it's Invoice's own logic\n# hidden in a module for the appearance of a \"skinny\" model. Put it back on Invoice.\n```\n\nA concern used by only one class is just moving code; it belongs in that class. A concern should be reusable across at least two unrelated models.\n\n## Anti-Patterns\n\n### God controllers\n\nAny controller past ~80 lines is doing too much. Split actions across controllers or extract to services.\n\n### Fat models with 30+ methods\n\nModels should know about their own data. Methods that orchestrate other models, send notifications, or coordinate workflows belong in services.\n\n### Callback chains\n\n`after_save :update_cache, :send_notifications, :enqueue_export` is the start of a debugging nightmare. Move them into a service that runs them explicitly.\n\n### Nested attributes for complex forms\n\n`accepts_nested_attributes_for` is fine for simple cases. For conditional validation or cross-model logic, use a form object.\n\n### Default scopes on critical models\n\n`default_scope { where(deleted: false) }` silently excludes records from every query in the app, including the ones you need for support and debugging. Prefer an explicit named scope.\n\n### Models named after database concepts\n\n`UserRole`, `OrderStatus`, `InvoiceState` are usually enum candidates, not models.\n\n### Reaching for a JS framework before Hotwire\n\nIf the page is server-rendered with occasional interactivity, Hotwire ships faster. Reserve React\u002FVue for genuinely SPA-shaped apps.\n\n## Best Practices\n\n- Keep controllers thin; push business logic into services.\n- Return Result objects from services so callers branch on outcome, not exceptions.\n- Wrap multi-record writes in a transaction; let notification\u002Fside-effect failures log without breaking the primary write.\n- Pass IDs to jobs, keep `perform` idempotent, set retry\u002Fdiscard explicitly.\n- Default to eager loading; treat an accidental N+1 as a bug, not a nuisance.\n- Reserve concerns for behavior shared across at least two unrelated models.\n- Reach for Hotwire before a client-side framework on server-rendered apps.\n\n## Related Skills\n\n- `backend-patterns` — service boundaries and adapter patterns (referenced by the Ruby patterns rules)\n- Ruby patterns rules (`rules\u002Fruby\u002Fpatterns.md`, installed as `rules\u002Fecc\u002Fruby\u002Fpatterns.md`) — the decisions and when-to-use guidance this skill implements\n","# Rails Patterns\n\nFramework patterns for modern Ruby on Rails applications (Rails 7.1+ and 8.x). Rails is opinionated by design; these are the patterns the community has converged on for apps that stay maintainable past the 50-model mark. This skill is the \"how.\" For the \"what\" and \"when\" (the decisions about which pattern to reach for), see the Ruby patterns rules — `rules\u002Fruby\u002Fpatterns.md` in this repository, installed as `rules\u002Fecc\u002Fruby\u002Fpatterns.md`.\n\n## When to Activate\n\n- Building a Rails application (full-stack, API-only, or hybrid)\n- Reviewing a PR that touches `app\u002F` or `config\u002F`\n- Generating models, controllers, services, or jobs\n- A controller action grows past ~10 lines\n- A model file grows past ~200 lines\n- ActiveRecord queries start appearing in controllers or views\n\n## Core Concepts\n\n### The directory contract\n\nRails apps follow a predictable structure. Add directories deliberately, not casually.\n\n```\napp\u002F\n  models\u002F         ActiveRecord models. Persistence and domain logic close to the data.\n  controllers\u002F    HTTP request handling. Thin orchestration only.\n  views\u002F          ERB templates. No business logic.\n  components\u002F     ViewComponent classes. View logic that needs tests.\n  services\u002F       Service objects. Multi-step business operations.\n  forms\u002F          Form objects. Complex form handling across multiple models.\n  queries\u002F        Query objects. Reusable, composable ActiveRecord queries.\n  jobs\u002F           Background jobs. Async work via Solid Queue, Sidekiq, or GoodJob.\n  mailers\u002F        ActionMailer classes.\n  helpers\u002F        View helpers. Tiny presentational logic only.\n  policies\u002F       Authorization policies (if using Pundit). Optional.\n  channels\u002F       ActionCable channels for WebSocket work.\n```\n\nAvoid `app\u002Flib\u002F`, `app\u002Futils\u002F`, `app\u002Fmanagers\u002F`. If something does not fit the directories above, the design usually needs rethinking, not a new directory. Truly generic code goes in `lib\u002F`.\n\n### Skinny controllers\n\nControllers receive a request, delegate to the right object, and render a response. Business logic lives elsewhere. (Per the Ruby patterns rules, extract to a service object when the controller starts carrying multiple responsibilities.)\n\n### Service objects\n\nThe default for business operations that touch more than a single model save. Conventions that keep them consistent:\n\n- Namespace by domain (`Invoices::Create`), not by suffix (`InvoiceCreator`).\n- A class method `.call` delegates to an instance `#call`.\n- Return a Result object, not a boolean or a bare record, so the caller can branch on success, errors, and the affected record.\n- Wrap multi-record writes in a transaction.\n- Keep each service single-purpose (`Invoices::Create`, `Invoices::MarkPaid`), never `Invoices::Manager`.\n\n### Form objects\n\nWhen a form spans multiple models or has fields that do not map to columns, use a form object rather than nested attributes or virtual attributes on the wrong model. It quacks like a model to the view (`form_with model: @form`) while composing records cleanly.\n\n### Query objects\n\nFor ActiveRecord queries reused across controllers or services, or too complex for a scope, extract a query object that accepts a scope as input so it composes. Rule of thumb: a scope that grows past three chained conditions or starts taking parameters wants to be a query object.\n\n### Background jobs\n\nOffload anything slow. (Per the Ruby patterns rules, Solid Queue for greenfield Rails 8 with modest throughput; Sidekiq when you need mature observability, high throughput, or existing Redis.) Regardless of adapter: pass IDs not records, make `perform` idempotent, and set `retry_on`\u002F`discard_on` explicitly.\n\n### ViewComponent over partials\n\nFor view logic with conditional rendering, more than two arguments, or reuse across more than three places, prefer a ViewComponent. Components are testable in isolation and surface their interface explicitly; partials with deep conditional logic become debt.\n\n### Hotwire: Turbo and Stimulus\n\nThe default Rails frontend stack. (Per the Ruby patterns rules, prefer Hotwire for server-rendered apps; reach for React\u002FVue only when interaction complexity justifies the client surface.) Turbo Frames for partial page updates, Turbo Streams for server-driven updates, Stimulus for small client-side behaviors next to the markup.\n\n### The Rails 8 Solid stack\n\nRails 8 ships database-backed defaults that previously needed Redis: Solid Queue (jobs), Solid Cache (cache), Solid Cable (ActionCable). The tradeoff is more database load for one fewer infrastructure component; a good fit for modest throughput, with Redis still winning at high scale. Kamal is the default Docker-based deploy tool.\n\n## Code Examples\n\n### Skinny controller with a service object\n\n```ruby\n# Bad: business logic in the controller\nclass InvoicesController \u003C ApplicationController\n  def create\n    @invoice = Invoice.new(invoice_params)\n    @invoice.user = current_user\n    @invoice.line_items.build(invoice_params[:line_items])\n    @invoice.tax_total = TaxCalculator.new(@invoice).calculate\n    @invoice.total = @invoice.line_items.sum(&:amount) + @invoice.tax_total\n\n    if @invoice.save\n      InvoiceMailer.created(@invoice).deliver_later\n      AccountingExportJob.perform_later(@invoice.id)\n      redirect_to @invoice, notice: \"Invoice created\"\n    else\n      render :new\n    end\n  end\nend\n\n# Good: controller orchestrates, service does the work\nclass InvoicesController \u003C ApplicationController\n  def create\n    result = Invoices::Create.call(params: invoice_params, user: current_user)\n\n    if result.success?\n      redirect_to result.invoice, notice: \"Invoice created\"\n    else\n      @invoice = result.invoice\n      render :new, status: :unprocessable_entity\n    end\n  end\nend\n```\n\n### The service object\n\n```ruby\n# app\u002Fservices\u002Finvoices\u002Fcreate.rb\nmodule Invoices\n  class Create\n    # Struct keeps this runnable on every Ruby that Rails 7.1 supports.\n    # On Ruby 3.2+, `Data.define(:success?, :invoice, :errors)` is a more\n    # concise immutable alternative.\n    Result = Struct.new(:success, :invoice, :errors, keyword_init: true) do\n      def success?\n        success\n      end\n    end\n\n    def self.call(params:, user:)\n      new(params: params, user: user).call\n    end\n\n    def initialize(params:, user:)\n      @params = params\n      @user = user\n    end\n\n    def call\n      invoice = build_invoice\n      ApplicationRecord.transaction do\n        invoice.save!\n      end\n      begin\n        send_notifications(invoice)\n      rescue StandardError => e\n        Rails.logger.error(\"Notification dispatch failed for invoice #{invoice.id}: #{e.message}\")\n      end\n      Result.new(success: true, invoice: invoice, errors: nil)\n    rescue ActiveRecord::RecordInvalid => e\n      Result.new(success: false, invoice: e.record, errors: e.record.errors)\n    end\n\n    private\n\n    attr_reader :params, :user\n\n    def build_invoice\n      invoice = user.invoices.new(params.except(:line_items))\n      invoice.line_items.build(params[:line_items])\n      invoice.tax_total = TaxCalculator.call(invoice)\n      invoice.total = invoice.line_items.sum(&:amount) + invoice.tax_total\n      invoice\n    end\n\n    def send_notifications(invoice)\n      InvoiceMailer.created(invoice).deliver_later\n      AccountingExportJob.perform_later(invoice.id)\n    end\n  end\nend\n```\n\n### Form object\n\n```ruby\n# app\u002Fforms\u002Fsignup_form.rb\nclass SignupForm\n  include ActiveModel::Model\n  include ActiveModel::Attributes\n\n  attribute :email, :string\n  attribute :password, :string\n  attribute :company_name, :string\n  attribute :terms_accepted, :boolean\n\n  validates :email, presence: true, format: URI::MailTo::EMAIL_REGEXP\n  validates :password, presence: true, length: { minimum: 12 }\n  validates :company_name, presence: true\n  validates :terms_accepted, acceptance: true\n\n  attr_reader :user, :company\n\n  def save\n    return false unless valid?\n\n    ApplicationRecord.transaction do\n      @company = Company.create!(name: company_name)\n      @user = @company.users.create!(email: email, password: password, role: :owner)\n    end\n    true\n  rescue ActiveRecord::RecordInvalid => e\n    errors.merge!(e.record.errors)\n    false\n  end\nend\n```\n\n### Query object\n\n```ruby\n# app\u002Fqueries\u002Finvoices\u002Foverdue.rb\nmodule Invoices\n  class Overdue\n    def self.call(scope: Invoice.all, as_of: Time.current)\n      new(scope: scope, as_of: as_of).call\n    end\n\n    def initialize(scope:, as_of:)\n      @scope = scope\n      @as_of = as_of\n    end\n\n    def call\n      scope\n        .where(status: :sent)\n        .where(due_date: ..as_of)\n        .where.not(id: paid_invoice_ids)\n        .includes(:customer, :line_items)\n    end\n\n    private\n\n    attr_reader :scope, :as_of\n\n    def paid_invoice_ids\n      Payment.where(created_at: ..as_of).pluck(:invoice_id)\n    end\n  end\nend\n```\n\nQuery objects accept a scope, so they compose: `Invoices::Overdue.call(scope: current_user.invoices)`.\n\n### N+1 prevention\n\n```ruby\n# Bad: N+1 in the view when it calls post.author.name\n@posts = Post.published\n\n# Good: eager load\n@posts = Post.published.includes(:author)\n```\n\n`includes` lets Rails choose preload vs eager_load. Force `preload` for separate queries, `eager_load` for a JOIN when filtering on the association. Since Rails 6.1, `strict_loading` raises on accidental lazy loads.\n\n### Counter cache\n\n```ruby\nclass Comment \u003C ApplicationRecord\n  belongs_to :post, counter_cache: true\nend\n```\n\n```ruby\nadd_column :posts, :comments_count, :integer, default: 0, null: false\n```\n\n`post.comments_count` becomes a column read instead of a `COUNT(*)`. This example\nassumes a new table; adding a counter cache to a table that already has rows requires a\nbackfill, which is out of scope here.\n\n### Background job shape\n\nPass record IDs, not records. Retries make delivery at-least-once, so any job that calls\nan external service must be idempotent — otherwise a transient failure after the remote\ncall succeeds will duplicate the effect on the next attempt.\n\n```ruby\nclass AccountingExportJob \u003C ApplicationJob\n  queue_as :exports\n\n  retry_on AccountingApi::TransientError, wait: :polynomially_longer, attempts: 5\n  discard_on AccountingApi::PermanentError\n\n  def perform(invoice_id)\n    invoice = Invoice.find(invoice_id)\n    export = AccountingExport.create_or_find_by!(\n      invoice: invoice,\n      idempotency_key: \"invoice-export-#{invoice.id}-#{invoice.updated_at.to_i}\"\n    )\n    return if export.completed_at?\n\n    receipt = AccountingApi.export(invoice, idempotency_key: export.idempotency_key)\n    export.update!(completed_at: Time.current, external_id: receipt.id)\n  end\nend\n```\n\n```ruby\nadd_index :accounting_exports, :idempotency_key, unique: true\n```\n\nThe unique index is what makes this safe: when two attempts race, the database rejects\nthe second insert and Active Record resolves the conflict inside the call, returning the\nexisting row. That happens without any job-level retry — `retry_on` above covers only\n`AccountingApi::TransientError`. The guard\ncovers the window before the remote call; passing `idempotency_key` through to the API\ncovers the window after it, so a crash between the API call and `update!` still resolves\nto a single export.\n\n### ViewComponent\n\n```ruby\n# app\u002Fcomponents\u002Finvoice_status_badge_component.rb\nclass InvoiceStatusBadgeComponent \u003C ViewComponent::Base\n  STATUS_CLASSES = {\n    draft: \"bg-gray-100 text-gray-800\",\n    sent: \"bg-blue-100 text-blue-800\",\n    paid: \"bg-green-100 text-green-800\",\n    overdue: \"bg-red-100 text-red-800\"\n  }.freeze\n\n  def initialize(invoice:)\n    @invoice = invoice\n  end\n\n  def call\n    tag.span(@invoice.status.humanize, class: \"rounded-full px-2 py-1 text-sm #{status_class}\")\n  end\n\n  private\n\n  def status_class\n    STATUS_CLASSES.fetch(@invoice.status.to_sym, \"bg-gray-100\")\n  end\nend\n```\n\n```erb\n\u003C%= render InvoiceStatusBadgeComponent.new(invoice: @invoice) %>\n```\n\n### Hotwire\n\n```erb\n\u003C%# Turbo Frame: clicking Edit replaces only this frame %>\n\u003C%= turbo_frame_tag \"invoice_#{@invoice.id}\" do %>\n  \u003Cdiv class=\"invoice\">\n    \u003C%= link_to \"Edit\", edit_invoice_path(@invoice) %>\n  \u003C\u002Fdiv>\n\u003C% end %>\n```\n\n```erb\n\u003C%# Turbo Stream: app\u002Fviews\u002Fcomments\u002Fcreate.turbo_stream.erb %>\n\u003C%= turbo_stream.append \"comments\", @comment %>\n\u003C%= turbo_stream.update \"comment_form\", partial: \"form\", locals: { comment: Comment.new } %>\n```\n\n```javascript\n\u002F\u002F app\u002Fjavascript\u002Fcontrollers\u002Fcopy_to_clipboard_controller.js\nimport { Controller } from \"@hotwired\u002Fstimulus\"\n\nexport default class extends Controller {\n  static targets = [\"source\"]\n\n  copy() {\n    navigator.clipboard.writeText(this.sourceTarget.value)\n  }\n}\n```\n\n### Acceptable vs unacceptable callbacks\n\n```ruby\n# Acceptable: pure data normalization\nclass User \u003C ApplicationRecord\n  before_validation :normalize_email\n\n  private\n\n  def normalize_email\n    self.email = email.to_s.downcase.strip\n  end\nend\n\n# Move to a service instead: side effects hidden in a callback\n# class User \u003C ApplicationRecord\n#   after_create :send_welcome_email  # hard to opt out of, hard to test\n# end\n```\n\n### Good concern vs bad concern\n\n```ruby\n# Good: genuinely cross-cutting, reusable across unrelated models\n# app\u002Fmodels\u002Fconcerns\u002Fsoft_deletable.rb\nmodule SoftDeletable\n  extend ActiveSupport::Concern\n\n  included do\n    scope :active, -> { where(deleted_at: nil) }\n    scope :deleted, -> { where.not(deleted_at: nil) }\n  end\n\n  def soft_delete! = update!(deleted_at: Time.current)\n  def restore! = update!(deleted_at: nil)\nend\n\n# Bad: a \"concern\" used by exactly one model, holding logic that belongs on it\n# app\u002Fmodels\u002Fconcerns\u002Finvoice_calculations.rb\nmodule InvoiceCalculations\n  extend ActiveSupport::Concern\n\n  def calculate_total\n    line_items.sum(&:amount) + tax_total\n  end\nend\n# Only Invoice includes this. It isn't cross-cutting; it's Invoice's own logic\n# hidden in a module for the appearance of a \"skinny\" model. Put it back on Invoice.\n```\n\nA concern used by only one class is just moving code; it belongs in that class. A concern should be reusable across at least two unrelated models.\n\n## Anti-Patterns\n\n### God controllers\n\nAny controller past ~80 lines is doing too much. Split actions across controllers or extract to services.\n\n### Fat models with 30+ methods\n\nModels should know about their own data. Methods that orchestrate other models, send notifications, or coordinate workflows belong in services.\n\n### Callback chains\n\n`after_save :update_cache, :send_notifications, :enqueue_export` is the start of a debugging nightmare. Move them into a service that runs them explicitly.\n\n### Nested attributes for complex forms\n\n`accepts_nested_attributes_for` is fine for simple cases. For conditional validation or cross-model logic, use a form object.\n\n### Default scopes on critical models\n\n`default_scope { where(deleted: false) }` silently excludes records from every query in the app, including the ones you need for support and debugging. Prefer an explicit named scope.\n\n### Models named after database concepts\n\n`UserRole`, `OrderStatus`, `InvoiceState` are usually enum candidates, not models.\n\n### Reaching for a JS framework before Hotwire\n\nIf the page is server-rendered with occasional interactivity, Hotwire ships faster. Reserve React\u002FVue for genuinely SPA-shaped apps.\n\n## Best Practices\n\n- Keep controllers thin; push business logic into services.\n- Return Result objects from services so callers branch on outcome, not exceptions.\n- Wrap multi-record writes in a transaction; let notification\u002Fside-effect failures log without breaking the primary write.\n- Pass IDs to jobs, keep `perform` idempotent, set retry\u002Fdiscard explicitly.\n- Default to eager loading; treat an accidental N+1 as a bug, not a nuisance.\n- Reserve concerns for behavior shared across at least two unrelated models.\n- Reach for Hotwire before a client-side framework on server-rendered apps.\n\n## Related Skills\n\n- `backend-patterns` — service boundaries and adapter patterns (referenced by the Ruby patterns rules)\n- Ruby patterns rules (`rules\u002Fruby\u002Fpatterns.md`, installed as `rules\u002Fecc\u002Fruby\u002Fpatterns.md`) — the decisions and when-to-use guidance this skill implements\n",{"name":5,"origin":24,"description":7},"community","main","15fa5201935d2b1d172b4e61c2360c908d876d20","plugins\u002Fbackend\u002Fskills\u002Frails-patterns",0,"https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP","https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fsfp-hive","https:\u002F\u002Fgithub.com\u002Fsiddu1004","I am a student at Amrita Vishwa Vidyapeetham pursuing my BTECH degree in Electronics and Electrical Engineering (2024-2028).","2026-11-09 16:04:40",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add siddu1004\u002FSFP --skill rails-patterns",{"tool":40,"command":41},"bunx","bunx skills add siddu1004\u002FSFP --skill rails-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add siddu1004\u002FSFP --skill rails-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fbackend\u002Fskills\u002Frails-patterns\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7FEEDADZBNBVY19H3XZKCBQ","scientific-schematics","Generates scientific diagram drafts using Nano Banana 2 AI with smart iterative refinement. Uses Gemini 3.7 Flash for quality review. Refines when the review requests improvement, with at most two generations. Specialized in neural network architectures, system diagrams, flowcharts, biological pathways, and complex scientific visualizations.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fscientific-schematics\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7FEE0JS04FE58MST48D0MMC","polyhaven-texture-apply","Apply realistic PBR textures from PolyHaven to any Blender object. Supports metals, wood, concrete, fabric, and more. Trigger when asked to texture an object, apply a material from PolyHaven, make something look like metal\u002Fwood\u002Fmarble, or change object surface.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-texture-apply\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7FEDJRWV194TY411WVRS84W","polyhaven-studio-setup","Set up a professional product photography studio in Blender using PolyHaven HDRIs and PBR ground materials. Trigger when asked to create a studio setup, add HDRI lighting, set up product photography, or create a showroom scene.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-studio-setup\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7FED5H2FGS50XGETMGSM0RV","polyhaven-scene-builder","Build complete product scenes using PolyHaven assets — HDRI environment, textured ground\u002Fpedestal, and optional props from the 3D model library. Trigger when asked to build a product scene, create a showcase setup, add a pedestal, or compose a product shot.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-scene-builder\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7FECSNZ2CJA7Z8TPE5R844R","polyhaven-material-swap","Cycle through multiple PolyHaven materials on a product and render each variant. Great for showing color\u002Ffinish options. Trigger when asked to show material variants, swap textures, create color options, show finish comparisons, or render product in different materials.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-material-swap\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7FECBPQ6YWH48PYAMS0C5CE","polyhaven-hdri-showcase","Render the same product across multiple HDRI environments and output a comparison grid. Trigger when asked to compare lighting setups, test different environments, show product in multiple settings, or create an HDRI comparison.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-hdri-showcase\u002FSKILL.md",[],[]]