Skip to content

Instantly share code, notes, and snippets.

@Aaron2Ti
Created June 19, 2010 08:22
Show Gist options
  • Save Aaron2Ti/444706 to your computer and use it in GitHub Desktop.
Save Aaron2Ti/444706 to your computer and use it in GitHub Desktop.
class ParentDoc
include Mongoid::Document
embeds_many :child_docs
field :statistic
field :children_order, :type => Array, :default => [] # hold all the children's id
end
class ChildDoc
include Mongoid::Document
embedded_in :parent_doc, :inverse_of => :child_docs
attr_writer :position
after_save :update_position
def position
exsited_position = parent_doc.children_order.index(id)
exsited_position ? exsited_position + 1 : parent_doc.aspects.size
end
def update_position
if @position && (@position.to_i > 0)
parent_doc.children_order.delete(id)
parent_doc.children_order.insert(@position.to_i - 1, id)
parent_doc.save
end
end
end
# in the console, run
>> p = ParentDoc.new
=> #<ParentDoc _id: 4c1c7d478d0f110597000017, children_order: [], statistic: nil>
>> p.save
=> true
>> p.child_docs
=> []
>> p.child_docs.create :position => 1
=> #<ChildDoc _id: 4c1c7d618d0f110597000018, >
>> ParentDoc.find(p.id).child_docs
=> [#<ChildDoc _id: 4c1c7d618d0f110597000018, >, #<ChildDoc _id: 4c1c7d618d0f110597000018, >]
# seems it created two identical objects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment