Module: WellFormed::NestedAttributes::ClassMethods

Defined in:
lib/well_formed/nested_attributes.rb

Instance Method Summary collapse

Instance Method Details

#nested_attribute_for(name, form_class = nil, &block) ⇒ Object

Defines a singular nested form for validating nested attributes on a has_one/belongs_to.

Both ‘name_attributes=` and `name=` setters are defined automatically.

Example — inline block:

class CreateOrderForm < WellFormed::Base
  include WellFormed::NestedAttributes
  nested_attribute_for :billing_address do
    attribute :street, :string
    validates :street, presence: true
  end
end


45
46
47
# File 'lib/well_formed/nested_attributes.rb', line 45

def nested_attribute_for(name, form_class = nil, &block)
  _register_nested(name, form_class, collection: false, &block)
end

#nested_attributes_for(name, form_class = nil) {|block| ... } ⇒ Object

Defines a collection nested form for validating nested attributes on a has_many association.

Both ‘name_attributes=` (Rails form_with / form_for) and `name=` (API, no suffix) setters are defined automatically — whichever key your params contain will work.

Records with ‘_destroy: true` are excluded from validation but forwarded to the resource.

Example — inline block:

class CreateOrderForm < WellFormed::Base
  include WellFormed::NestedAttributes
  nested_attributes_for :line_items do
    attribute :name, :string
    validates :name, presence: true
  end
end

Parameters:

  • name (Symbol)

    the association name (e.g. :line_items)

  • form_class (Class, nil) (defaults to: nil)

    a ResourceForm class. Omit when supplying a block.

Yield Parameters:

  • block

    inline class body evaluated on an anonymous WellFormed::Base subclass.



29
30
31
# File 'lib/well_formed/nested_attributes.rb', line 29

def nested_attributes_for(name, form_class = nil, &block)
  _register_nested(name, form_class, collection: true, &block)
end

#registered_nested_attributesObject



49
50
51
52
# File 'lib/well_formed/nested_attributes.rb', line 49

def registered_nested_attributes
  inherited = superclass.respond_to?(:registered_nested_attributes) ? superclass.registered_nested_attributes : {}
  inherited.merge(@registered_nested_attributes ||= {})
end