Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining postgres_ext (or Rails 4) arrays with associations

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)?

like image 964
Nuck Avatar asked Mar 14 '13 04:03

Nuck


2 Answers

At this point, there isn't a way to use relationships with arrays in Rails. Using the selected answer though, you will run into the N+1 select issue. Say you get your posts and then the tags for it on each post with "tags" method defined in the class. For each post you call the tags on, you will incur another database hit.

Hopefully, this will change in the future and we can get rid of the join table (especially given that Postgres 9.4 will include support for foreign keys in Arrays).

like image 175
sat Avatar answered Oct 20 '22 06:10

sat


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.

like image 42
mhenrixon Avatar answered Oct 20 '22 06:10

mhenrixon