How to declare a scope based on embedded model attributes with Mongoid

Viewed 376

I have a User model which embeds a Profile:

# app/models/user.rb
class User
  embeds_one :profile
end

# app/models/profile.rb
class Profile
  embedded_in :user, inverse_of: :profile
  field :age, type: integer
end

Now I want to declare a scope in User which can list out all users whose profile.age is > 18.

3 Answers

You can query attributes of embedded documents via:

User.where(:'profile.age'.gt => 18)

or as a scope:

class User
  embeds_one :profile

  scope :adults, -> { where(:'profile.age'.gt => 18) }
end

When you use embeds you can access only associated B objects of A. So, your need i.e all B where age>x doesn't work. So, go for has_one and belongs_to

A.rb

class A
  has_one :b
  scope :adults, -> { Bar.adults }
end

B.rb

class B
 field :age ,type:integer
 belongs_to :a
 scope :adults, -> { where(:age.gt=> 18)}
end
Related