Sha256: edda0ba947eda100c5addb0246c6906e2dc3f6fcf7472c457b490d01886e9c42

Contents?: true

Size: 1.57 KB

Versions: 46

Compression:

Stored size: 1.57 KB

Contents

module Avo
  module Fields
    class HasOneField < BaseField
      attr_accessor :relation_method
      attr_accessor :display

      def initialize(id, **args, &block)
        super(id, **args, &block)

        hide_on :new, :edit

        @placeholder ||= I18n.t "avo.choose_an_option"

        @relation_method = name.to_s.parameterize.underscore
        @display = args[:display].present? ? args[:display] : :show
      end

      def label
        value.send(target_resource.title)
      end

      def resource
        target_resource
      end

      def turbo_frame
        "#{self.class.name.demodulize.to_s.underscore}_#{display}_#{id}"
      end

      def frame_url
        "#{Avo::App.root_path}/resources/#{@model.model_name.route_key}/#{@model.id}/#{id}/#{value.id}?turbo_frame=#{turbo_frame}"
      end

      def target_resource
        if @model._reflections[id.to_s].klass.present?
          Avo::App.get_resource_by_model_name @model._reflections[id.to_s].klass.to_s
        elsif @model._reflections[id.to_s].options[:class_name].present?
          Avo::App.get_resource_by_model_name @model._reflections[id.to_s].options[:class_name]
        else
          Avo::App.get_resource_by_name id.to_s
        end
      end

      def fill_field(model, key, value, params)
        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

46 entries across 46 versions & 1 rubygems

Version Path
avo-1.18.2 lib/avo/fields/has_one_field.rb
avo-1.18.2.pre.0 lib/avo/fields/has_one_field.rb
avo-1.18.1 lib/avo/fields/has_one_field.rb
avo-1.18.0 lib/avo/fields/has_one_field.rb
avo-1.18.0.pre.3 lib/avo/fields/has_one_field.rb
avo-1.18.0.pre.2 lib/avo/fields/has_one_field.rb
avo-1.18.0.pre.1 lib/avo/fields/has_one_field.rb
avo-1.17.1 lib/avo/fields/has_one_field.rb
avo-1.17.0 lib/avo/fields/has_one_field.rb
avo-1.16.4 lib/avo/fields/has_one_field.rb
avo-1.16.3 lib/avo/fields/has_one_field.rb
avo-1.16.2 lib/avo/fields/has_one_field.rb
avo-1.16.1 lib/avo/fields/has_one_field.rb
avo-1.16.0 lib/avo/fields/has_one_field.rb
avo-1.15.0 lib/avo/fields/has_one_field.rb
avo-1.15.0.pre.1 lib/avo/fields/has_one_field.rb
avo-1.14.0 lib/avo/fields/has_one_field.rb
avo-1.13.3 lib/avo/fields/has_one_field.rb
avo-1.13.2 lib/avo/fields/has_one_field.rb
avo-1.13.1 lib/avo/fields/has_one_field.rb