2

here is a simple structure:

class Dinner
  belongs_to :user
  field :name

class User
  has_many :dinners
  field :name

now, what i want is to find all the dinners hosted by 'John'. looking for something like:

Dinner.where('user.name' => 'john')

the problem is that i cannot find any way to query by referenced attribute. any suggestions?

5
  • Dinner.includes(:user).where(:name => 'john') Is this not working? Commented Jan 31, 2013 at 4:34
  • @SachinR, no because Dinner also can have the name attrubute Commented Jan 31, 2013 at 5:11
  • Dinner.includes(:user).where("user.name = ? ", 'john') Commented Jan 31, 2013 at 5:18
  • @SachinR you confuse it with active record stuff. you can't do it on mongoid. Commented Jan 31, 2013 at 5:32
  • Can you provide all the conditions you require for the query? Commented Feb 1, 2013 at 10:00

1 Answer 1

3

I think it just won't work with your model. AFAIK querying by nested attributes works only for embedded documents. You have two options:

Dinner.where(user: User.find_by(name: 'john'))

Or store user name directly in Dinner. It's redundant, but makes your query simplier.

MongoDB is not relational database and doesn't support joins.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.