Sha256: 349d7d467b952f6a5f64d2911794f4b8d41bf934c7ddcf816e43b1bccd203a8c

Contents?: true

Size: 1.98 KB

Versions: 4

Compression:

Stored size: 1.98 KB

Contents

module Avo
  module Fields
    class BelongsToField < Field
      attr_accessor :searchable
      attr_accessor :relation_method

      def initialize(name, **args, &block)
        @defaults = {
          component: 'belongs-to-field',
          placeholder: I18n.t('avo.choose_an_option')
        }

        @searchable = args[:searchable] == true ? true : false
        @relation_method = name.to_s.parameterize.underscore

        super(name, **args, &block)
      end

      def hydrate_field(fields, model, resource, view)
        return fields if model_or_class(model) == 'class'

        fields[:searchable] = @searchable
        fields[:is_relation] = true
        fields[:database_id] = foreign_key model
        target_resource = App.get_resources.find { |r| r.class == "Avo::Resources::#{name}".safe_constantize }

        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) if relation_model.present?
          fields[:database_value] = relation_model[:id] if relation_model.present?
          fields[:link] = Avo::Resources::Resource.show_path(relation_model)
        end

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

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

        fields[:plural_name] = target_resource.plural_name

        fields
      end

      def foreign_key(model)
        if model.class == Class
          model.reflections[@relation_method].foreign_key
        else
          model.class.reflections[@relation_method].foreign_key
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
avo-0.4.4 lib/avo/app/fields/belongs_to.rb
avo-0.4.3 lib/avo/app/fields/belongs_to.rb
avo-0.4.2 lib/avo/app/fields/belongs_to.rb
avo-0.4.1 lib/avo/app/fields/belongs_to.rb