Created
May 17, 2013 14:36
-
-
Save ichilton/5599450 to your computer and use it in GitHub Desktop.
Mongoid Embedded Documents
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
2x classes - Topic and TopicTerm | |
Topic embeds many topic_terms | |
I can find topics by using elemMatch: | |
def self.find_by_ref(reference) | |
where({:topic_terms => {'$elemMatch' => {:references => /^#{reference}(?:\.[0-9]+|$)/}}}) | |
end | |
I then get an array of Topic objects back, where I can do: | |
topic.topic_terms - to get all of the terms back for that topic. | |
But what I want is an instance variable which contains the matching topics, but only those terms which match. | |
(so out of 65 terms, a topic might only have 1 term which matches the ref - so I want just that one). | |
I have a class method on TopicTerm which finds those: | |
def self.find_by_bible_ref(reference) | |
where(:references.in => [/^#{reference}(?:\.[0-9]+|$)/]) | |
end | |
But I can't work out how to get an object back which will contain only matching terms. | |
I'm trying to do an API call with RABL views as follows: | |
get '/ref/:book.:chapter(.:verse)/terms', :rabl => 'topic_terms' do | |
ref = [ params[:book], params[:chapter], params[:verse] ].join('.') | |
@topics = paginate(Topic.find_by_ref(ref)) | |
end | |
and then a RABL view of: | |
collection @topics | |
attributes :id, :name | |
child :topic_terms => :terms do | |
attributes :id, :name, :heading, :references, :individual_references | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My solution in the end was to pass ref into the rabl view and do this:
Anyone have a neater solution?