Today I Learned

A Zero One initiative

2 posts by nelsonpascoal

Query Postgres Array field with SQL & ActiveRecord

If you have, for example a string array column in Postgres you can do a query match on any of the array values columns with a SQL query like this:

SELECT * FROM table WHERE 'value' = ANY(str_field);

This will return records where the string ‘value’ is present in at least one of the array string values stored in str_field

Equivalent query in ActiveRecord

ArModel.where("? = ANY(str_field)", "value")

You can also use ALL to match all values in an array column.

PG Gem fails on Mac OS 11.x (Big Sur)

If after installing pg gem in your ruby project and you get the following error with the pg gem

Library not loaded: libpq.5.dylib

You can fix the linking issues by running the following commands:

cd ~/[your ruby path]/versions/2.7.2/lib/ruby/gems/2.7.0/gems/pg-1.2.3/lib

install_name_tool -change libpq.5.dylib /Library/PostgreSQL/12/lib/libpq.5.12.dylib pg_ext.bundle

You may need to modify the commands above to suite your ruby manager and currently installed versions.