Created
December 15, 2010 05:10
-
-
Save xaviershay/741657 to your computer and use it in GitHub Desktop.
dm-test.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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