[英]How to use OR in Rails 4 ActiveRecord named scope
我的項目中有course
和category
模型。 Course
有很多categories
, category
有很多courses
。
在course
模型中,我具有一個范圍:search_by_category
,它將使用類別的名稱,並在課程的類別名稱等於名稱的情況下找到該課程。
scope :search_by_category, -> (name){
joins(:categories).where('categories.name = ?', name) if name.present?
}
如果我有一個名字,該范圍可以正常工作。 但是,當我有一個名稱數組時,它會中斷,因為where('categories.name = ?', "Some name", "Some other name", "Some more name")
是無效的SQL語法。
在嘗試過Rails控制台后,我發現需要使用OR。
例如
where('categories.name = name[0] OR categories.name = name[1])
我該如何重寫我的范圍以實現此目標,或者我可以嘗試其他方法嗎?
嘗試這個:
array_with_names = ["Some name", "Some other name", "Some more name"]
where('categories.name in (?)', array_with_names)
如果要使用OR
運算符,請使用名稱創建數組並使用*
splat運算符:
array_with_names = ["Some name", "Some other name", "Some more name"]
where('categories.name = ? OR categories.name = ? OR categories.name = ?', *array_with_names)
但是我認為這沒用。
為此使用Rails語法。 ActiveRecord將自動檢測到您正在使用數組,並將為您構造適當的SQL語法(無論使用IN
還是=
)。
scope :search_by_category, -> (array_with_names){
joins(:categories).where(categories: { name: array_with_names })
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.