[英]Rails: better way to check for associated object by name
我的產品型號中有以下方法:
def has_feature? (feature_name)
self.features.where(:name=>feature_name).present?
end
這似乎很慢。 有沒有更好的方法來檢查我的產品是否具有給定名稱的功能?
另一種寫這種方法的方法是在Feature
模型中使用范圍,看它是否有幫助並做present?
在該范圍的結果輸出上
scope :includes_feature, lambda{ |feature|
{ :name => feature }
}
所以你最后可以做的是product.features.includes_feature(feature_name)
.present?
是不是在一個標准方法ActiveRecord::Relation
是什么where
的回報。 打電話給.present?
獲取具有給定名稱的所有功能,更改為數組然后調用.present?
在陣列上。
如果你打電話給.exists?
相反,所執行的數據庫查詢稍微優化一下,以檢查該功能是否存在。
但是,我不確定你會注意到這兩個選項之間的性能差異很大。 最可能的原因是您缺少數據庫索引。 假設您的關聯是Product has_many :features
將通過features.product_id
和features.name
上的索引來改進將生成的數據庫查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.