Rails: Multiple "has_many through" for the two same models?

Posted by neezer on Stack Overflow See other posts from Stack Overflow or by neezer
Published on 2010-03-30T02:34:45Z Indexed on 2010/03/30 2:43 UTC
Read the original article Hit count: 404

Filed under:
|

Can't wrap my head around this...

class User < ActiveRecord::Base
  has_many :fantasies, :through => :fantasizings
  has_many :fantasizings, :dependent => :destroy
end

class Fantasy < ActiveRecord::Base
  has_many :users, :through => :fantasizings
  has_many :fantasizings, :dependent => :destroy
end

class Fantasizing < ActiveRecord::Base
  belongs_to :user
  belongs_to :fantasy
end

... which works fine for my primary relationship, in that a User can have many Fantasies, and that a Fantasy can belong to many Users.

However, I need to add another relationship for liking (as in, a User "likes" a Fantasy rather than "has" it... think of Facebook and how you can "like" a wall-post, even though it doesn't "belong" to you... in fact, the Facebook example is almost exactly what I'm aiming for).

I gathered that I should make another association, but I'm kinda confused as to how I might use it, or if this is even the right approach. I started by adding the following:

class Fantasy < ActiveRecord::Base

  ...

  has_many :users, :through => :approvals
  has_many :approvals, :dependent => :destroy
end

class User < ActiveRecord::Base

  ...

  has_many :fantasies, :through => :approvals
  has_many :approvals, :dependent => :destroy
end

class Approval < ActiveRecord::Base
  belongs_to :user
  belongs_to :fantasy
end

... but how do I create the association through Approval rather than through Fantasizing?

If someone could set me straight on this, I'd be much obliged!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about associations