如何检查存储数组的列是否'includes'传递给"where"的参数?



所以我有一个Question模型,其中包含以下列:

#  refactor_rules          :string           default([]), is an Array

存储如下值:

>> Question.offset(1).last.refactor_rules
=> ["dry", "concise"]

我想编写一个where查询来检查是否有任何问题在该refactor_rules属性中包含单个参数/选项。

我尝试了这个查询:

@questions = Question.includes(:user, :answer).where(refactor_rules: params[:rule])

但这没有用。它给了我以下错误:

PG::InvalidTextRepresentation: ERROR:  malformed array literal: "dry"

我知道AR期待一个string,但得到一个数组。

我只是不太清楚如何根据传入的字符串"dry"或"简洁"检查该属性的每个值。

编辑 1

问题模型

class Question < ApplicationRecord
  belongs_to :user
  belongs_to :accepted_answer, class_name: "Answer", dependent: :destroy
  has_many :answers, dependent: :destroy
end

应答模型

class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :user
  has_one :answered_question, class_name: "Question", foreign_key: "accepted_answer_id"    
end

如果你在谈论Postgresql数组列,看看这篇博客文章,它很好地总结了在rails下使用这种类型的列。

您应该能够使用以下语法查找具有任何匹配refactor_rule的记录:

Question.where("? = ANY (refactor_rules)", params[:rule])

有关更多文档,请参阅 ANY 运算符。

最新更新