2

I have a stage table that has a jsonb column named title.

The value of title is a ruby hash value, e.g. {en: "A", de: "A" }

Now I wrote the following scope for searching a stage based on the title in the Rails model

scope :search, ->(query) { where('title @> ?', { "#{I18n.locale}": "%#{query}%" }.to_json).any? }

but it does not work and it's giving me all items in the RSpec test.

1 Answer 1

3

You need to use the ->> JSON operator together with ILIKE to do pattern matching:

scope :search, ->(query) {
  where("title->>'#{I18n.locale}' ILIKE ?", "%#{query}%")
}
Sign up to request clarification or add additional context in comments.

5 Comments

but I got this error message ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for #<Arel::Nodes::Count:0x00005578ffa1a3b0>) in: title->>en ILIKE ?
@kia Ah, I shouldn't have wrapped the string in Arel.sql. Edited.
now I got this error ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "en" does not exist LINE 1: SELECT "stages".* FROM "stages" WHERE (title->>en ILIKE '%A1... bacause I access title in backe-end like this -> title[:en]
Ah sorry. The key name needs to be quoted title->>'en' ILIKE ?. sqlfiddle.com/#!17/58944b/5
also, we should write SQL query with sanitize_sql for passing from brakeman

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.