簡體   English   中英

如何在Rails 4 ActiveRecord命名范圍中使用OR

[英]How to use OR in Rails 4 ActiveRecord named scope

我的項目中有coursecategory模型。 Course有很多categoriescategory有很多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.

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