4

I'm using Rails 4 and am trying to implement a Notif model which should have an array of users that have seen it.

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. 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.

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? I guess I'm simply trying to store an array of user ids in my notif model.

Ely
  • 10,860
  • 4
  • 43
  • 64
Vasseurth
  • 6,354
  • 12
  • 53
  • 81
  • possible duplicate of [rails 3, activerecord, any "gotchas" if use has\_many WITHOUT corresponding belongs\_to?](http://stackoverflow.com/questions/4925827/rails-3-activerecord-any-gotchas-if-use-has-many-without-corresponding-belon) – Ely Jun 30 '15 at 22:56
  • 2
    There's [a deleted answer which actually explains the workaround](http://i.imgur.com/7UvWBcX.png) OP is asking about, but was deleted after a single downvote which is a shame. Many others have already explained the dangers of such an approach. It's sad to see relevant answers downvoted instead of improving them with an edit or comment. – Dennis Apr 24 '16 at 21:06

2 Answers2

1

It is technically possible - but it's not how ActiveRecord works and it won't save you money.

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.

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.

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.

max
  • 96,212
  • 14
  • 104
  • 165
1

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

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.

Collin Graves
  • 2,207
  • 15
  • 11