簡體   English   中英

你如何在 Rails 中使用 LIKE 查詢枚舉?

[英]How do you use LIKE query for enum in rails?

我已將枚舉 task_status 設置為:

class ConfirmedTask < ApplicationRecord
  enum task_status: {pending: 1, complete: 2}
end

現在我必須使用搜索參數“掛起”來搜索所有處於掛起狀態的任務。 我正在使用 pg_search 進行搜索,但它不適用於枚舉,所以我想使用 LIKE 查詢進行查詢:

ConfirmedTask.where('task_status like ?', '%pend%')

但這給了我錯誤

ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR: operator does not exist: integer ~~ unknown) LINE 1: ...asks".* FROM "confirmed_tasks" WHERE (task_status like '%pen: No運算符匹配給定的名稱和參數類型。您可能需要添加顯式類型轉換。

有什么建議么?

如果你想在這里使用枚舉,那么你需要將你的枚舉值作為字符串存儲在數據庫中。 目前,您的列task_status具有integer類型。 因此您無法使用 LIKE 運算符進行搜索。 要解決它,請進行此更改。

  enum task_status: {pending: 'pending', complete: 'complete'}

並將task_status列的類型設置為 db 中的string 但如果可能的話,我建議你從前端發送值的全名。

枚舉通常以整數形式存儲在數據庫中。 到 label 的映射是在應用程序級別完成的。 數據庫不知道標簽。

這意味着您必須弄清楚哪些標簽符合您在應用程序級別的標准。 然后將它們轉換為它們的 integer 值(在數據庫中使用)。 實現此目的的一種方法是將grep與符合您要求的正則表達式結合使用。

# find the matching labels
labels = ConfirmedTask.task_statuses.keys.grep(/pend/i)
# convert them into their integer values
values = labels.map(&ConfirmedTask.task_statuses)
# create your query
ConfirmedTask.where('task_status IN (?)', values)

將 label 放到價值轉換中並讓 Rails 解決這個問題會更容易一些。 這可以通過將標簽數組傳遞給普通的where調用(使用非 SQL 字符串參數)來完成。

# find the matching labels
labels = ConfirmedTask.task_statuses.keys.grep(/pend/i)
# pass labels to `where` and let Rails do the label -> integer conversion
ConfirmedTask.where(task_status: labels)

我不是 100% 確定是否允許字符串數組作為枚舉屬性的where條件。 該文檔使用符號 如果上述方法不起作用,則 map 使用.map(&:to_sym)將字符串轉換為符號。

暫無
暫無

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

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