Sha256: 894cb907d302d42814786e9b799a615cbf78c8b130e5e905febd8340ffd6ea92

Contents?: true

Size: 1.89 KB

Versions: 8

Compression:

Stored size: 1.89 KB

Contents

module Form
  class Field < ActiveRecord::Base
    include Admin::Form::Field

    # mapped to simple_form 'as:' option
    TYPES ||= %w[ string text email ]

    self.table_name_prefix = 'form_'
    self.inheritance_column = nil

    belongs_to :structure, touch: true
    has_many :fields, through: :structure

    delegate :count, to: :fields, prefix: true
    delegate :header, to: :structure

    after_create ::Callbacks::Form::FieldAfterCreate.new
    after_destroy ::Callbacks::Form::FieldAfterDestroy.new
    before_update ::Callbacks::Form::FieldBeforeUpdate.new, if: :position_changed?
    after_update :update_column_header, if: :default_label_changed_but_not_position?

    with_options presence: true do
      validates :type, inclusion: { in: TYPES }
      validates :structure
      validates :position, numericality: { greater_than_or_equal_to: 0}
      with_options on: :create do
        validates :position, numericality: { less_than_or_equal_to: :fields_count }
      end
      with_options on: :update do
        validates :position, numericality: { less_than: :fields_count }
      end
    end

    def column_key
      :"column_#{position}"
    end

    def label
      send("label_#{I18n.locale}")
    end

    def default_label
      send("label_#{I18n.default_locale}")
    end

    def input_type
      type.demodulize.underscore.to_sym
    end

    def type_enum
      TYPES
    end

    def update_header
      attributes = RailsAdminCMS::Config.custom_form_max_size.times.map do |i|
        [:"column_#{i}", '']
      end.to_h

      fields.map do |field|
        attributes[field.column_key] = field.default_label
      end

      header.update! attributes
    end

    private

    def default_label_changed_but_not_position?
      send("label_#{I18n.default_locale}_changed?") && !position_changed?
    end

    def update_column_header
      header.update! column_key => default_label
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
rails_admin_cms-0.1.1 app/models/form/field.rb
rails_admin_cms-0.0.9 app/models/form/field.rb
rails_admin_cms-0.0.7 app/models/form/field.rb
rails_admin_cms-0.0.6 app/models/form/field.rb
rails_admin_cms-0.0.5 app/models/form/field.rb
rails_admin_cms-0.0.4 app/models/form/field.rb
rails_admin_cms-0.0.3 app/models/form/field.rb
rails_admin_cms-0.0.2 app/models/form/field.rb