简体   繁体   English

没有belongs_to的Rails has_many

[英]Rails has_many without a belongs_to

I'm using Rails 4 and am trying to implement a Notif model which should have an array of users that have seen it. 我正在使用Rails 4并且我正在尝试实现一个Notif模型,该模型应该有一组已经看过它的用户。

My idea is to use a has_many relationship ( notif has_many :users ) where I add users which have seen the notif to the users . 我的想法是使用has_many关系( notif has_many :users ),我在其中添加已经向用户看过通知的users The current issue I'm experiencing is that I cannot call @notif.users because it states column users.notif_id does not exist since I'm not using a belongs_to . 我遇到的当前问题是我无法调用@notif.users因为它声明column users.notif_id does not exist因为我没有使用belongs_to

One solution is to use a many-to-many relationship; 一种解决方案是使用多对多关系; however, I'd like to avoid having to create an individual association for each user that views a notification (trying to save database space). 但是,我想避免为每个查看通知的用户创建单独的关联(尝试保存数据库空间)。

Is there a way to effectively have a users field without the has_many relationship? 有没有办法有效地拥有一个没有has_many关系的users字段? I guess I'm simply trying to store an array of user ids in my notif model. 我想我只是想在我的notif模型中存储一组用户id。

It is technically possible - but it's not how ActiveRecord works and it won't save you money. 这在技术上是可行的 - 但它不是ActiveRecord的工作方式,也不会为您省钱。

Not all databases actually support array types. 并非所有数据库都支持数组类型。 Without array types you would have to store the ids in a string, which pretty much eliminates any effective form of querying and joins. 如果没有数组类型,则必须将id存储在字符串中,这几乎消除了任何有效的查询和连接形式。

Even the DBs that support arrays don't really support storing foreign keys in arrays. 即使是支持数组的数据库也不支持在数组中存储外键。 This means you can kiss referential integrity goodbye. 这意味着你可以亲吻参照完整性再见。 Indexing arrays might not work either. 索引数组也可能无法正常工作。

Add to this the fact that you can't use Rails associations without major hacks. 除此之外,您无法在没有重大攻击的情况下使用Rails关联。

I hope you realize by now that it's a pretty stupid plan to save money. 我希望你现在意识到省钱是一个非常愚蠢的计划。 Especially since database space is cheap compared to developer time. 特别是因为与开发者时间相比,数据库空间便宜。

IF you're using a relational database, although this is a correct omnidirectional relationship, ActiveRecord isn't going to play very nicely with you (if at all). 如果你正在使用关系数据库,虽然这是一个正确的全向关系,但ActiveRecord不会很好地与你玩(如果有的话)。

Also, it's important to note that, in the year 2015, trying to find an omnidirectional ActiveRecord workaround is far more expensive than the extra database entries. 此外,值得注意的是,在2015年,尝试查找全向ActiveRecord解决方法比额外的数据库条目要昂贵得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM