Reputation: 93
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
.
Upvotes: 3
Views: 418
Reputation: 2675
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
Upvotes: 1
Reputation: 114218
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
Upvotes: 2
Reputation: 6572
This should save your day -))
Class B
field :age, type:integer
scope :adults, -> { where(:age.gt => 18) }
end
class A
embed_one :b
def embed_adults
b.adults
end
end
https://mongoid.github.io/old/en/mongoid/docs/querying.html#scoping
Upvotes: 0