Skip to content

Instantly share code, notes, and snippets.

@ichilton
Created May 17, 2013 14:36
Show Gist options
  • Save ichilton/5599450 to your computer and use it in GitHub Desktop.
Save ichilton/5599450 to your computer and use it in GitHub Desktop.
Mongoid Embedded Documents
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
@ichilton
Copy link
Author

My solution in the end was to pass ref into the rabl view and do this:

node(:terms) do |t|
  if @ref
    partial(topic_term', :object => t.topic_terms.find_by_ref(@ref))
  else
    partial('topic_term', :object => t.topic_terms)
  end
end

Anyone have a neater solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment