Combining postgres_ext (or Rails 4) arrays with associations

postgres-ext, postgresql, rails-activerecord, ruby-on-rails-4

Solution

All you really need to do is

def tags
  Tag.where(id: tag_ids)
end

def add_tag(tag)
  self.tag_ids += [tag.id] unless tag_ids.include?(tag.id)
end

At least that's what I do at the moment. I do some pretty cool stuff with hashes (hstore) as well with permissions. One way of handling tags is to create the has_many through and persist the tags in a string array column as they are added for convenience and performance (not having to query the 2 related tables just to get the names out). I you don't necessarily have to use active record to do cool stuff with the database.

Problem

I'm trying to develop a many-to-many relationship between tags (in the `tags` table) and items (in the `items` table) using a field of type `integer[]` on each item. I know that Rails 4 (and Rails 3 via postgres_ext) has support for Postgres' arrays feature through the `:array => true` parameter, but I can't figure out how to combine them with Active Record associations. Does `has_many` have an option for this? Is there a gem for this? Should I give up and just create a `has_many :through` relationship (though with the amount of relations I'm expecting this is probably unmanageable)?

Original source