I have a ATable ( id, value ) with value type is json
id | value
--------------------------------------------------
1 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [283, 237, 238] }
2 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [283, 234, 545, 23] }
3 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [98, 56, 2] }
4 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [28345, 100, 333, 987] }
I wrote ATable.where("value->>'user_ids' LIKE ?", "%283%")
Results:
id | value
--------------------------------------------------
1 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [283, 237, 238] }
2 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [283, 234, 545, 23] }
4 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [28345, 100, 333, 987] }
Expecting result:
id | value
--------------------------------------------------
1 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [283, 237, 238] }
2 | { 'start': '2023-10-02', 'end': '2023-10-05', user_ids: [283, 234, 545, 23] }
I try ATable.where("value->>'user_ids' LIKE In (?)", "283") but not working
Thanks.
Not a PG expert but the problem with using
"%283%"is that it will match any number containing those digits. That’s why the row with id 4 is returned (28345).Try the
@>operator in conjunction with->:Docs
Not sure this should be tagged as a Rails question, definitely not as a Ruby question.