Tagging in Rails 4 using Postgres Arrays

Updated . Posted . Visible to the public.

Usage:

class Document < ActiveRecord::Base
  scope :any_tags, -> (tags){ where('tags && ARRAY[?]', tags) }
  scope :all_tags, -> (tags){ where('tags @> ARRAY[?]', tags) }
end

Document.create(title: "PostgreSQL", tags: ["pg","rails"])

Document.any_tags('pg')
Document.all_tags(['pg', 'rails'])

Migration:

class CreateDocuments < ActiveRecord::Migration
  def change
    create_table :documents do |t|
      t.string :title
      t.string :tags, array: true, default: []
      t.timestamps
    end
    add_index  :documents, :tags, using: 'gin'
  end
end

More examples here and here.

Last edit
Jonas Schiele
Keywords
psql
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2014-10-15 13:25)