Module: ROM::Plugins::Relation::Changeset::InstanceMethods

Defined in:
changeset/lib/rom/plugins/relation/changeset.rb

Overview

Relation instance methods provided by the Changeset plugin

Instance Method Summary collapse

Instance Method Details

#changeset(type, data) ⇒ Changeset #changeset(changeset_class, data) ⇒ Changeset

Create a changeset for a relation

Overloads:

  • #changeset(type, data) ⇒ Changeset

    Create a changeset of one of predefined types

    Examples:

    creating a record

    users.
      changeset(:create, name: 'Jane').
      commit
    # => #<ROM::Struct::User id=1 name="Jane">

    updating a record

    users.
      by_pk(1).
      changeset(:update, name: 'Jack').
      commit
    # => #<ROM::Struct::User id=1 name="Jane">

    providing data as a separate step

    changeset = users.changeset(:create)
    jack = changeset.data(name: 'Jack').commit
    jane = changeset.data(name: 'Jane').commit

    using a command graph

    users.
      changeset(
        :create,
        name: "Jane",
        posts: [{ title: "Something about aliens" }]
      )

    Parameters:

    • type (Symbol)

      The changeset type

    • data (Hash)

    Returns:

  • #changeset(changeset_class, data) ⇒ Changeset

    Examples:

    using a custom changeset class

    class NewUser < ROM::Changeset::Create
      map do |tuple|
        { **tuple, name: tuple.values_at(:first_name, :last_name).join(' ') }
      end
    end
    
    users.changeset(NewUser, first_name: 'John', last_name: 'Doe').commit

    Parameters:

    • changeset_class (Class)

      A custom changeset class

    Returns:



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'changeset/lib/rom/plugins/relation/changeset.rb', line 83

def changeset(type, data = EMPTY_HASH)
  klass = type.is_a?(Symbol) ? TYPES.fetch(type) : type

  unless klass < ROM::Changeset
    raise ArgumentError, "+#{type.name}+ must be a Changeset descendant"
  end

  if klass < ROM::Changeset::Stateful
    klass.new(self, __data__: data)
  else
    klass.new(self)
  end
rescue KeyError
  raise ArgumentError,
        "+#{type.inspect}+ is not a valid changeset type. Must be one of: #{TYPES.keys.inspect}"
end