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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)