Reputation: 33755
So I have a Question
model that has the following column:
# refactor_rules :string default([]), is an Array
That stores values like this:
>> Question.offset(1).last.refactor_rules
=> ["dry", "concise"]
I would like to write a where
query that checks to see if any question includes a single parameter/option in that refactor_rules
attribute.
I tried this query:
@questions = Question.includes(:user, :answer).where(refactor_rules: params[:rule])
But that didn't work. It gave me the following error:
PG::InvalidTextRepresentation: ERROR: malformed array literal: "dry"
I know it's something with AR is expecting a string
, but is instead getting an array.
I just can't quite figure out how to check each value for that attribute against the string "dry" or "concise" that is passed in.
Edit 1
Question Model
class Question < ApplicationRecord
belongs_to :user
belongs_to :accepted_answer, class_name: "Answer", dependent: :destroy
has_many :answers, dependent: :destroy
end
Answer Model
class Answer < ApplicationRecord
belongs_to :question
belongs_to :user
has_one :answered_question, class_name: "Question", foreign_key: "accepted_answer_id"
end
Upvotes: 0
Views: 395
Reputation: 15944
If you are talking about Postgresql array column, take a look at this blog post which nicely summarizes using this type of column under rails.
You should be able to find records with any matching refactor_rule
with the following syntax:
Question.where("? = ANY (refactor_rules)", params[:rule])
See the ANY
operator for more docs.
Upvotes: 1