David Sigley
David Sigley

Reputation: 1198

Multiple polymorphic associations on the same Model(s), how do I access the correct rows?

I have a model, Post, which has a Posted and a Received (I.E a Sender and a Recipient). Both Posted and Received can be either a User or a Group.

So

User.rb
  has_many :posts, as: :posted
  has_many :posts, as: :received

Group.rb
  has_many :posts, as: :posted
  has_many :posts, as: :received

Post.rb
  belongs_to :posted, polymorphic: true
  belongs_to :received, polymorphic: true

Is this possible? It seems to make sense to me and I have no problem making a post, but I can't seem to access the posts to display.

I thought I could use: (but reading more on polymorphic associations.. I suspect I don't fully understand it)

@user.recieved do |post|
and
@user.posted do |post|

Thanks

Upvotes: 1

Views: 611

Answers (1)

infused
infused

Reputation: 24337

You can do it, you'll just need to differentiate the has_many association names:

User.rb
  has_many :posted_posts, class_name: 'Post', as: :posted
  has_many :received_posts, class_name: 'Post', as: :received

Group.rb
  has_many :posted_posts, class_name: 'Post', as: :posted
  has_many :received_posts, class_name: 'Post', as: :received

Post.rb
  belongs_to :posted, polymorphic: true
  belongs_to :received, polymorphic: true

So, to use them:

@user.posted_posts do |post|

end

@user.received_posts do |post|

end

You can name the associations whatever you want, but keep in mind that you can't have more than one association with the same name on a model.

Upvotes: 3

Related Questions