簡體   English   中英

如何在Mongoid中建立復雜的范圍

[英]How to build complex scopes in Mongoid

我對Mongoid有點陌生,我正在嘗試在模型中建立一種復雜的作用域。 我希望能夠做這樣的事情:

scope :for_currency, ->(currency){ where(price.currency.iso_code: currency.iso_code) }

我想要此作用域的模型命名為PaymentTerm ,它與Price模型具有has_one關系,而Price模型則屬於 Currency模型。 如您所見,我正在嘗試獲取PaymentTerms ,其中Price的價格具有Currency ISO編碼,該Iso值是我作為參數傳遞給塊的值。

有誰知道實現此目標的有效方法? 非常感謝,

認為您應該定義一種解決方法

def self.for_currency(currency)
  self.all.select {|pt| pt.currency.iso_code == currency.iso_code }
end

它將返回一個數組結果,但不會返回mongoid :: Criteria。 我建議如果此作用域經常使用,請在PaymentTerm模型中創建一個新字段來保存此代碼,例如field :currency_iso_code ,然后

scope :for_currency, ->(currency){ where(currency_iso_code: currency.iso_code) }

冗余數據將使速度更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM