Read more

Tagging in Rails 4 using Postgres Arrays

Thomas Klemm
October 15, 2014Software engineer

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'])
Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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 Show archive.org snapshot and here Show archive.org snapshot .

Posted by Thomas Klemm to makandra dev (2014-10-15 15:25)