Sha256: 5fb8a2db07a3b9e9391d0f9af3f5a6df45a80c0417a9857e77788a29b0c560cc

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

module Madmin
  class Field
    module Associatable
      class << self
        def included(_base)
          attr_reader :association_class
          attr_reader :association_display_value
          attr_reader :association_foreign_key
          attr_reader :association_scope
        end
      end

      def initialize(args)
        super(args)
        implement_association!
      end

      def association_collection
        association_class.send(association_scope)
      end

      def association_id_for(resource)
        value_for(resource).id
      end

      def association_id_or_blank_for(resource)
        value_for(resource).try(:id)
      end

      def association_param
        ActiveModel::Naming.param_key(association_class)
      end

      def association_slug
        Object.const_get("::Madmin::Resources::#{association_class}").new.slug
      end

      def association_value_for(resource)
        value_for(resource).send(association_display_value)
      end

      def strong_params_keys
        [association_foreign_key]
      end

      private

      def implement_association!
        association = model.reflect_on_all_associations.find { |assc| assc.name == key }

        @association_class         = association.klass
        @association_display_value = option_or_default(:display_value, :name)
        @association_foreign_key   = association.foreign_key
        @association_scope         = :all
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
madmin-0.1.0 lib/madmin/field/associatable.rb