Sha256: 9857ef8f256865ae8fa5794179b1fb7e16e54f6eb82f6a38c3e4c2636c131318

Contents?: true

Size: 1.94 KB

Versions: 10

Compression:

Stored size: 1.94 KB

Contents

module Avo
  module Fields
    class HasOneField < Field
      attr_accessor :relation_method

      def initialize(name, **args, &block)
        @defaults = {
          updatable: true,
          component: 'has-one-field',
        }

        super(name, **args, &block)

        hide_on :create

        @placeholder = I18n.t 'avo.choose_an_option'

        @relation_method = name.to_s.parameterize.underscore
      end

      def hydrate_field(fields, model, resource, view)
        target_resource = get_related_resource(resource)
        fields[:relation_class] = target_resource.class.to_s

        relation_model = model.public_send(@relation_method)

        if relation_model.present?
          relation_model = model.public_send(@relation_method)
          fields[:value] = relation_model.send(target_resource.title)
          fields[:database_value] = relation_model[:id]
          fields[:link] = Avo::Resources::Resource.show_path(relation_model)
        end

        # Populate the options on show and edit
        fields[:options] = []

        if [:edit, :create].include? view
          fields[:options] = target_resource.model.all.map do |model|
            {
              value: model.id,
              label: model.send(target_resource.title)
            }
          end
        end

        fields[:plural_name] = target_resource.plural_name

        fields
      end

      def get_related_resource(resource)
        class_name = resource.model.reflections[name.to_s.downcase].class_name
        App.get_resources.find { |r| r.class == "Avo::Resources::#{class_name}".safe_constantize }
      end

      def fill_field(model, key, value)
        if value.blank?
          related_model = nil
        else
          related_class = model.class.reflections[name.to_s.downcase].class_name
          related_model = related_class.safe_constantize.find value
        end

        model.public_send("#{key}=", related_model)

        model
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
avo-0.4.10 lib/avo/app/fields/has_one.rb
avo-0.4.9 lib/avo/app/fields/has_one.rb
avo-0.4.8 lib/avo/app/fields/has_one.rb
avo-0.4.7 lib/avo/app/fields/has_one.rb
avo-0.4.6 lib/avo/app/fields/has_one.rb
avo-0.4.5 lib/avo/app/fields/has_one.rb
avo-0.4.4 lib/avo/app/fields/has_one.rb
avo-0.4.3 lib/avo/app/fields/has_one.rb
avo-0.4.2 lib/avo/app/fields/has_one.rb
avo-0.4.1 lib/avo/app/fields/has_one.rb