Search code examples
ruby-on-railsrubyactiverecordhas-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.

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.


Solution

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