Skip to content

Association Extension

Dillon Welch edited this page Mar 7, 2023 · 4 revisions

The Subroutine::AssociationFields module provides an interface for loading ActiveRecord instances easily.

require "subroutine/association_fields"

class UserUpdateOp < ::Subroutine::Op
  include ::Subroutine::AssociationFields

  association :user

  with_options groups: "update" do
    string :first_name 
    string :last_name
  end

  protected

  def perform
    user.update_attributes(update_params)
  end
end
require "subroutine/association_fields"

class RecordTouchOp < ::Subroutine::Op
  include ::Subroutine::AssociationFields

  association :record, polymorphic: true

  protected

  def perform
    record.touch
  end
end

For non-polymorphic associations, the foreign key type of an association is dynamically determined using metadata from the inferred foreign key field. For polymorphic associations, the foreign key type by default only supports numeric types. However, for all types of associations, the type can be overridden via the foreign_key_type configuration value. For example:

require "subroutine/association_fields"

class UserUpdateOp < ::Subroutine::Op
  include ::Subroutine::AssociationFields

  association :user, foreign_key_type: :string

  with_options groups: "update" do
    string :first_name 
    string :last_name
  end

  protected

  def perform
    user.update_attributes(update_params)
  end
end

Configuration options:

  • class_name - specifies the name of the association class when it's unable to be inferred properly
  • find_by - specifies what column to look up the association by
  • foreign_key - specifies the name of the foreign key of the association
  • foreign_key_type - specifies the column type of the foreign key
  • polymorphic - the association is polymorphic (model_id + model_type lookup)
  • unscoped - adds .unscoped to lookups

A large set of example association configurations can be found here

Clone this wiki locally