0

I have in Rails a jsonb column on table profile with the following structure

add_column :profile, :properties, :jsonb, default: {}

user.build_profile(
  properties: {
    languages: [
        {name: "German", level: 3}, 
        {name: "Russian", level: 2},
        {name: "English", level: 3}
    ],
    skills: ['Alpha', 'Beta', 'Gamma']
  }
)

user.build_profile(
  properties: {
    languages: [
        {name: "German", level: 2}, 
        {name: "Russian", level: 3},
        {name: "Spanish", level: 3}
    ],
    skills: ['Alpha','Beta']
  }
)


user.build_profile(
  properties: {
    languages: [
        {name: "Italian", level: 2}, 
        {name: "Spanish", level: 3}
    ],
    skills: ['Gamma']
  }
)

I am able to retrieve one Language like so

@profiles.where("properties @> ?", {'languages': [{'name':'German'}] }.to_json)

and multiple skills (x OR y) like so

@profiles.where("properties -> 'skills' ?| array[:skills]", skills: ['Alpha', 'Beta'])

BUT I need to retrieve MULTIPLE languages query term German and Russian

How can I achieve?

Thanks in advance

1 Answer 1

1

Not familiar with JSONB but ActiveRecord does support an and operator like

@profiles.where("properties @> ?", {'languages': [{'name':'German'}] }.to_json).
  and(@profiles.where("properties @> ?", {'languages': [{'name':'Russian'}] }.to_json))

https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-and

Sign up to request clarification or add additional context in comments.

1 Comment

I have consider this option before made the question, but since none was able to found out an other elegeant way, i ll pick your answer. thanks

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.