Skip to content

Instantly share code, notes, and snippets.

@xaviershay
Created December 15, 2010 05:10
Show Gist options
  • Select an option

  • Save xaviershay/741657 to your computer and use it in GitHub Desktop.

Select an option

Save xaviershay/741657 to your computer and use it in GitHub Desktop.
dm-test.rb
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, 'postgres://localhost/test') # createdb test
class User
include DataMapper::Resource
property :id, Serial
has 1, :user_profile
def self.ranked
order = DataMapper::Query::Direction.new(user_profile.ranking, :desc)
query = all.query # Access a blank query object for us to manipulate
query.instance_variable_set("@order", [order])
# Force the user_profile model to be joined into the query
query.instance_variable_set("@links", [relationships['user_profile'].inverse])
all(query) # Create a new collection with the modified query
end
end
class UserProfile
include DataMapper::Resource
property :user_id, Integer, :key => true
property :ranking, Integer, :default => 0
belongs_to :user
end
DataMapper.finalize
DataMapper.auto_migrate!
User.create(:user_profile => UserProfile.new(:ranking => 2))
User.create(:user_profile => UserProfile.new(:ranking => 5))
User.create(:user_profile => UserProfile.new(:ranking => 3))
puts User.ranked.all(:limit => 1).map {|x| x.user_profile.ranking }.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment