class Aform::Model

Public Class Methods

build_klass(params, validations, builder = Aform::Builder.new(Aform::Model)) click to toggle source
# File lib/aform/model.rb, line 13
def self.build_klass(params, validations, builder = Aform::Builder.new(Aform::Model))
  builder.build_model_klass(params, validations)
end
model_name() click to toggle source
# File lib/aform/model.rb, line 17
def self.model_name
  ActiveModel::Name.new(self, nil, "Aform::Model")
end
new(object, form, attributes = {}, destroy_key = :_destroy) click to toggle source
# File lib/aform/model.rb, line 5
def initialize(object, form, attributes = {}, destroy_key = :_destroy)
  @destroy = attributes.delete(destroy_key)
  @object = object
  @form = form
  sync_with_model
  @attributes.merge! attributes_for_save(attributes)
end
validates_uniqueness_of(*attr_names) click to toggle source
# File lib/aform/model.rb, line 21
def self.validates_uniqueness_of(*attr_names)
  validates_with UniquenessValidator, _merge_attributes(attr_names)
end

Public Instance Methods

save(association = nil) click to toggle source

AR saves children with parent if it's new object but dont save children with parent when children is updated

# File lib/aform/model.rb, line 27
def save(association = nil)
  @object.assign_attributes(@attributes)
  if @destroy
    @object.destroy
  else
    association << @object if association
    @object.save
  end
end
valid?() click to toggle source
Calls superclass method
# File lib/aform/model.rb, line 37
def valid?
  @destroy || super
end

Private Instance Methods

attributes_for_save(attributes) click to toggle source
# File lib/aform/model.rb, line 48
def attributes_for_save(attributes)
  attrs = attributes.symbolize_keys
  params.inject({}) do |memo, p|
    field_name = get_field_name(p)
    if @form.respond_to?(p[:field])
      memo.merge(field_name => @form.public_send(p[:field], attrs))
    else
      if attrs.has_key?(p[:field])
        memo.merge(field_name => attrs[p[:field]])
      else
        memo
      end
    end
  end
end
get_field_name(p) click to toggle source
# File lib/aform/model.rb, line 64
def get_field_name(p)
  if p.has_key?(:options) && p[:options].has_key?(:model_field)
    p[:options][:model_field]
  else
    p[:field]
  end
end
sync_with_model() click to toggle source
# File lib/aform/model.rb, line 43
def sync_with_model
  attrs = @object.attributes.symbolize_keys
  @attributes = attributes_for_save(attrs)
end