Reputation: 19723
How can I do an embeds_many
if a field is of a specific value? For example. Lets assume a member of the family can have one or many cars if
they are older than or equal to 18 years of age.
class FamilyMember
include Mongoid::Document
# Psuedo code
embeds_many :cars, :if :age >= 18
field :member_type, :type => String # can be dad, mom, son, daughter
field :age, :type => Integer
end
Is such a thing possible or would I have to go through some other means. i.e. validation?
Upvotes: 0
Views: 218
Reputation: 4053
try this and take a look here for more information
embeds_many :cars do
def with_age(age=18)
where(age: age)
end
end
then you have to use, something like this family_member.cars.with_age(18)
or family_member.cars.with_age
, and then you can modify condition as per your need.
Upvotes: 2
Reputation: 2653
embeds_many :cars, :if => :check_age
def check_age
return true if self.age >= 18
end
Upvotes: 0
Reputation:
In active record you could do
has_many :cars, :conditions => ['age >= ?', 18]
I have not tried it in mongoid though.
Upvotes: 0