2017-03-01 50 views
0

以下代碼給出了一個空的範圍。 Category_ids是一個類別數組。如何爲數組創建範圍?

scope :art, ->{ where(:category_ids => '1') } 

如何檢查數組中是否存在其中一個類別?

+0

你在用什麼數據庫? Postgres/MySQL/...? –

回答

0
  1. 得到類別
  2. 糾正你在那裏查詢

例子:

has_many :categories 
scope :art, -> { required = [Category.first]; where(categories: required) } 

我認爲在你的模型,你有categories關聯。在這種情況下,您可以在where查詢中使用categories: requiredrequired應該設置爲你想要的類別數組

0

你說category_ids是一個類別數組(我假設類別ID的)。你是否試圖返回所有具有該數組中的類別ID的記錄?如果是這樣,你正在尋找:

scope :art, -> { where (:category_id => category_ids) } 

或者與新的Ruby語法:

scope :art, -> { where(category_id: category_ids) } 

如果我誤解,你正在尋找爲1的類ID的任何記錄,那麼你正在尋找:

scope :art, -> { where(category_id: '1') }