Module: CustomFields::Types::BelongsTo::Target::ClassMethods

Defined in:
lib/custom_fields/types/belongs_to.rb

Instance Method Summary collapse

Instance Method Details

#apply_belongs_to_custom_field(klass, rule) ⇒ Object

Adds a belongs_to relationship between 2 models

Parameters:

  • klass (Class)

    The class to modify

  • rule (Hash)

    It contains the name of the field and if it is required or not



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/custom_fields/types/belongs_to.rb', line 36

def apply_belongs_to_custom_field(klass, rule)
  # puts "#{klass.inspect}.belongs_to #{rule['name'].inspect}, class_name: #{rule['class_name'].inspect}" # DEBUG

  position_name = "position_in_#{rule['name'].underscore}"

  # puts "#{klass.inspect}.field :#{position_name}" # DEBUG

  klass.field position_name, type: ::Integer, default: 0

  klass.belongs_to rule['name'].to_sym, class_name: rule['class_name']

  if rule['required']
    klass.validates_presence_of rule['name'].to_sym
  end

  klass.before_create do |object|
    position = (object.class.max(position_name.to_sym) || 0) + 1
    object.send(:"#{position_name}=", position)
  end
end