public
Created

  • Download Gist
mongo_association_finders.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
module FromParam
extend ActiveSupport::Concern
 
module ClassMethods
def [](key)
find_by_slug(key) || find_by_id(key)
end
 
def from_param(param)
self[param]
end
 
def from_param!(param)
from_param(param) or raise MongoMapper::DocumentNotFound
end
end
end
 
MongoMapper::Document.plugin(FromParam)
 
class Post
include MongoMapper::Document
key :slug
many :comments
end
 
class Comment
include MongoMapper::Document
key :slug
belongs_to :post
end
 
post = Post.create(:slug => 'post')
com1 = Comment.create(:slug => 'comment1', :post => post)
com2 = Comment.create(:slug => 'comment1', :post => post)
 
# This raises an ArgumentError as expected b/c Comment does respond_to :from_param
Post.first.comments.from_param
 
# However, because from_param doesn't return a Plucky::Query, it continues up the
# method missing chain.
Post.first.comments.from_param('comment1')

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.