Skip to content

Instantly share code, notes, and snippets.

@emmanuel
Created June 9, 2011 17:56
Show Gist options
  • Select an option

  • Save emmanuel/1017306 to your computer and use it in GitHub Desktop.

Select an option

Save emmanuel/1017306 to your computer and use it in GitHub Desktop.
DataMapper: order results by a property on a ManyToMany relationship
DataMapper::Logger.new($stdout, :default)
DataMapper.setup(:default, "sqlite::memory:")
class Author
include DataMapper::Resource
property :id, Serial
property :email, String
has n, :posts
has n, :comments
has n, :post_comments, :through => :posts, :via => :comments, :model => "Comment", :inverse => :post_author
end
class Post
include DataMapper::Resource
property :id, Serial
property :body, String
belongs_to :author
has n, :comments
end
class Comment
include DataMapper::Resource
property :id, Serial
property :body, String
belongs_to :author
belongs_to :post
has 1, :post_author, :through => :post, :via => :author, :model => "Author", :inverse => :post_comments
end
DataMapper.auto_migrate!
# This works, but it's a bit inconvenient to be this explicit
# Author.all(:order => Author.comments.body.desc, :fields => [Author.id, Author.email], :links => [Author.relationships[:comments].inverse])
# This is as terse as I could get the ordering on a :through (ManyToMany) relationship
Author.all(:order => Author.post_comments.body.desc, :links => [Author.relationships[:comments].inverse])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment