[英]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. 我正在尝试使用每个项目上的
integer[]
类型的字段来开发标记(在tags
表中)和项目(在items
表中)之间的多对多关系。
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. 我知道Rails 4(和通过postgres_ext的Rails 3)通过
:array => true
参数支持Postgres的数组功能,但我无法弄清楚如何将它们与Active Record关联结合起来。
Does has_many
have an option for this? has_many
有这个选项吗? 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)? 我应该放弃并且只是创建一个
has_many :through
关系(虽然关系数量我预计这可能是无法管理的)?
At this point, there isn't a way to use relationships with arrays in Rails. 此时,没有办法在Rails中使用与数组的关系。 Using the selected answer though, you will run into the N+1 select issue.
但是,使用所选答案,您将遇到N + 1选择问题。 Say you get your posts and then the tags for it on each post with "tags" method defined in the class.
假设您使用类中定义的“tags”方法获取帖子,然后在每个帖子上为其添加标签。 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). 希望这将在未来发生变化,我们可以摆脱连接表(特别是考虑到Postgres 9.4将包括对Arrays中的外键的支持)。
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.
我用哈希(hstore)和权限做了一些非常酷的东西。 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).
处理标记的一种方法是创建has_many,并将标记保留在字符串数组列中,因为它们是为了方便和性能而添加的(不必查询2个相关表只是为了获取名称)。 I you don't necessarily have to use active record to do cool stuff with the database.
我不一定要使用活动记录来对数据库做很酷的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.