Skip to content

Instantly share code, notes, and snippets.

@arekt
Created May 27, 2010 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arekt/416369 to your computer and use it in GitHub Desktop.
Save arekt/416369 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'mongo_mapper'
MongoMapper.connection = Mongo::Connection.new('localhost',27017)
MongoMapper.database = "test"
class Word
include MongoMapper::Document
key :content, String
key :translation_ids, Array
many :translations, :in => :translation_ids do
def ordered_like_in_translation_ids
sort_by {|a| proxy_owner.translation_ids.index(a.id)}
end
end
end
class Translation
include MongoMapper::Document
key :content, String
key :lang, String
def random
rand
end
end
Word.collection.remove
Translation.collection.remove
w = Word.new(:content => "1")
w.translations = [Translation.new(:content => "one",:lang=>"pl"), Translation.new(:content=>"two"), Translation.new(:content => "three",:lang=>"ja")]
w.save
puts Word.first.translations.map(&:content).inspect
puts "Lets make translation_ids reverse"
w=Word.first
w.translation_ids.reverse!;
w.save
w.reload
puts "order haven\'t changed"
puts Word.first.translations.map(&:content).inspect
puts "but when we use ordered_like_in_translation_ids method ...."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment