Sagiv Ofek
Sagiv Ofek

Reputation: 25280

Mongoid query by reference attribute

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?

Upvotes: 2

Views: 807

Answers (1)

cthulhu
cthulhu

Reputation: 3726

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.

Upvotes: 3

Related Questions