Reputation: 1620
I'm a bit new to Mongoid and I'm trying to build a kind of complex scope in my model. I want to be able to do something like this:
scope :for_currency, ->(currency){ where(price.currency.iso_code: currency.iso_code) }
The model I want this scope for, named PaymentTerm, has a has_one relationship to a Price model, which belongs_to a Currency model. And as you can see I'm trying to get the PaymentTerms where its Price has a Currency ISO coded with the value I'm passing as a parameter to the block.
Does anyone knows a great and valid approach to achieve this?. Many thanks,
Upvotes: 2
Views: 423
Reputation: 888
Think you should define a method to solve it
def self.for_currency(currency)
self.all.select {|pt| pt.currency.iso_code == currency.iso_code }
end
it will return a array result but not a mongoid::Criteria. And I suggest that if this scope used frequently, create a new field in PaymentTerm
model to save this code like field :currency_iso_code
, then
scope :for_currency, ->(currency){ where(currency_iso_code: currency.iso_code) }
redundant data will make more faster speed.
Upvotes: 3