🛤️ Ruby on Rails - PostgreSQL Arrays
Updated at 2015-09-07 00:08
Ruby on Rails supports PostgreSQL arrays out of the box.
class AddNicknamesToUser < ActiveRecord::Migration
def change
change_table :users do |t|
t.text :nicknames, array: true, default: []
end
end
end
user = User.find(1)
user.update_attributes(nicknames: ['Ruksi'])
user.update_attributes(nicknames: user.nicknames.push('Ruxjin'))
# array contains this array
User.where('nicknames @> ARRAY[?]', ['Johnny']) # no
User.where('nicknames @> ARRAY[?]', ['Ruxjin']) # matches
User.where('nicknames @> ARRAY[?]', ['Doe', 'Ruxjin']) # no
User.where('nicknames @> ARRAY[?]', ['Ruksi', 'Ruxjin']) # matches
# array contains a single element from this array, overlap
User.where('nicknames && ARRAY[?]', ['Doe', 'Ruxjin', 'Johnny']) # matches
# is column is any of the following values
User.where('name = ANY(ARRAY[?])', ['John Doe', 'Ruksi Laine']) # matches
# if you defined column as string, you must covert the array to varchar[]
#User.where('nicknames @> ARRAY[?]::varchar[]', ['Doe', 'Ruxjin'])