Module: ActiveRecord::Embedding

Extended by:
ActiveSupport::Concern
Defined in:
lib/active_record/embedding.rb,
lib/active_record/embedding/version.rb

Overview

Allows embedding of ActiveRecord models.

Embedding other ActiveRecord models is a composition of the two and leads to the following behaviour:

  • Nested attributes are accepted on the parent without the _attributes suffix

  • Mass assignment security allows the embedded attributes

  • Embedded models are destroyed with the parent when not appearing in an update again

  • Embedded documents appears in the JSON output

  • Embedded documents that are deleted are not visible to the parent anymore, but will be deleted after save has been caled

You have to manually include this module

modified by Markus Fenske <[email protected]>

Examples:

class Invoice
  include ActiveRecord::Embedding

  embeds_many :items
end

Author:

  • Michael Kessler

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#as_json(options = { }) ⇒ Object

Add the embedded document in JSON serialization

Parameters:

  • options (Hash) (defaults to: { })

    the rendering options



131
132
133
# File 'lib/active_record/embedding.rb', line 131

def as_json(options = { })
  super({ :include => self.class.embeddings }.merge(options || { }))
end

#attributes=(attrs) ⇒ Object

Sets the attributes

Parameters:

  • new_attributes (Hash)

    the new attributes



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/active_record/embedding.rb', line 91

def attributes=(attrs)
  return unless attrs.is_a?(Hash)

  # Create a copy early so we do not overwrite the argument
  new_attributes = attrs.dup

  mark_for_destruction(new_attributes)

  self.class.embeddings.each do |embed|
    if new_attributes[embed]
      new_attributes["#{embed}_attributes"] = new_attributes[embed]
      new_attributes.delete(embed)
    end
  end

  super(new_attributes)
end

#update_attributes(attributes) ⇒ Object

Update attributes and destroys missing embeds from the database.



114
115
116
# File 'lib/active_record/embedding.rb', line 114

def update_attributes(attributes)
  super(mark_for_destruction(attributes))
end

#update_attributes!(attributes) ⇒ Object

Update attributes and destroys missing embeds from the database.



123
124
125
# File 'lib/active_record/embedding.rb', line 123

def update_attributes!(attributes)
  super(mark_for_destruction(attributes))
end