Combining postgres_ext (or Rails 4) arrays with associations

I am trying to create a relationship between tags (in the tags table) and elements (in the items table) using a field of type integer[] for each element.

I know that Rails 4 (and Rails 3 via postgres_ext) supports the function of Postgres arrays through the parameter :array => true , but I cannot figure out how to combine them with Active Record associations.

Does has_many option for this? Is there a stone for this? Should I give up and just create a has_many :through relationship (although with the number of relationships I expect, this is probably unmanageable)?

+6
source share
2 answers

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 what I am doing at the moment. I do some pretty cool stuff with hashes (hstore) as well as permissions. One way to handle tags is to create has_many through and save the tags in a row array column, as they are added for convenience and performance (without having to query 2 related tables to get the names). I don't have to use active recording to do cool things with the database.

+4
source

At this point, there is no way to use array relationships in Rails. However, using the selected answer, you will encounter the problem of choosing N + 1. Let's say you receive your messages, and then the tags for it at each post with the "tags" method defined in the class. For each message that you call in tags, you will suffer a different database hit.

I hope that this will change in the future, and we can get rid of the connection table (especially considering that Postgres 9.4 will include support for foreign keys in arrays).

+5
source

All Articles