Module: AcceptsNestedIds::ClassMethods

Defined in:
lib/accepts_nested_ids.rb

Instance Method Summary collapse

Instance Method Details

#accepts_nested_ids_for(*args) ⇒ Object

Sets up defered save and dirty tracking for the specified associations

Examples:

When class_name can be inferred from association name

include AcceptsNestedIds
accepts_nested_ids_for :documents, :users

When class_name is different from association name

include AcceptsNestedIds
accepts_nested_ids_for :documents, included_users: "User"

Parameters:

  • args (Array)


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/accepts_nested_ids.rb', line 49

def accepts_nested_ids_for(*args)
  @_nested_id_associations = map_nested_id_associations(*args)

  nested_id_associations.each do |nested_id_association|

    # Define ids_attr getter
    #
    # @example Method definition
    #   def document_ids
    #     @document_ids || (documents.loaded? ? documents.map(&:id) : documents.pluck(:id))
    #   end
    #
    define_method("#{nested_id_association.ids_attr}") do
      association = send(nested_id_association.attr)
      instance_variable_get("@#{nested_id_association.ids_attr}") ||
        (association.loaded? ? association.map(&:id) : association.pluck(:id))
    end

    # Define ids_attr setter
    #
    # @example Method definition
    #   def document_ids=(value)
    #     return if document_ids == value
    #     attribute_will_change!('document_ids')
    #     @document_ids = value
    #   end
    #
    define_method("#{nested_id_association.ids_attr}=") do |value|
      return if send(nested_id_association.ids_attr) == value
      attribute_will_change!(nested_id_association.ids_attr)
      instance_variable_set("@#{nested_id_association.ids_attr}", value)
    end

  end
end

#nested_id_associationsObject



85
86
87
# File 'lib/accepts_nested_ids.rb', line 85

def nested_id_associations
  @_nested_id_associations
end