meow
meow

Reputation: 28174

Mongoid Syntax Questions

1) Finding by instance object

Assuming I have the instance object called @topic. I want to retrieve the answers for this given topic. I was thinking I should be able to pass in :topics=>@topic, but i had to do the very ugly query below.

  @answers = Answers.where(:topic_ids => {"$in" => [@topic.id]})

2) Getting the string representation of the id. I have a custom function (shown below). But shouldn't this be a very common requirement?

  def sid
    return id.to_s
  end

Upvotes: 1

Views: 499

Answers (1)

bowsersenior
bowsersenior

Reputation: 12574

If your associations are set up correctly, you should be able to do:

@topic.answers

It sounds like the above is what you are looking for. Make sure you have set up your associations correctly. Mongoid is very forgiving when defining associations, so it can seem that they are set up right when there is in fact a problem like mismatched names in references_many and referenced_in.

If there's a good reason why the above doesn't work and you have to use a query, you can use this simple query:

@answers = Answer.where(:topic_ids => @topic.id)

This will match any Answer record whose topic_ids include the supplied ID. The syntax is the same for array fields as for single-value fields like Answer.where(:title => 'Foo'). MongoDB will interpret the query differently depending on whether the field is an array (check if supplied value is in the array) or a single value (check if the supplied value is a match).

Here's a little more info on how MongoDB handles array queries: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

Upvotes: 2

Related Questions