manojchowdary27
manojchowdary27

Reputation: 93

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

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

Answers (3)

krishna raikar
krishna raikar

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

Stefan
Stefan

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

marmeladze
marmeladze

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

Related Questions