0

I have a 3 models

  • User
  • Journal
  • Post

A couple of things can be assumed about these

  • User has_many :journals
  • Journal has_many :posts

I would like users to be able to subscribe to other users and specific journals on my site.

I am thinking I need a Polymorphic Subscription model that looks something like this

class CreateSubscriptions < ActiveRecord::Migration
  def change
    create_table :subscriptions do |t|
      t.integer :user_id
      t.references :subscribable, :polymorphic=>true
      t.timestamps
    end
  end
end

But here's where I'm stuck. I don't know how to setup the polymorphic relationships in my User model.

I want to be able to get the following things:

  • @user.watched_users
  • @user.watched_journals
  • @user.followers
  • @journal.followers

Can someone help? The docs are kind sparse on this and I know these can be a real chore to setup.

^_^

Mulan
  • 129,518
  • 31
  • 228
  • 259
  • 2
    The rails guides are pretty clear on how to do this, check out http://guides.rubyonrails.org/association_basics.html#polymorphic-associations – sunkencity Jul 30 '12 at 06:45
  • That only explains part of the issue, it doesn't speak of relationships that are both polymorphic and self-referential (self joins). – Craig C. Aug 06 '13 at 18:11

1 Answers1

1

While I understand the desire to want to just have the user subscribe to arbitrary objects, in practice, you'll end up dealing with these different subscriptions differently, so at least for now (until you find yourself wanting to subscribe to other objects on the site), just leave them separate (YAGNI).

You can do this through a simple join table for each relationship. the answer on How do I do reflexive self-join relationships in ActiveRecord? leads to a good example in http://railscasts.com/episodes/163-self-referential-association

Community
  • 1
  • 1
Ben Taitelbaum
  • 7,343
  • 3
  • 25
  • 45