views:

155

answers:

1

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!

+1  A: 

Keep your first set of code, then in your User Model add:

has_many :approved_fantasies, :through => :fantasizings, :source => :fantasy, :conditions => "fantasizings.is_approved = 1"

In your Fantasizing table, add an is_approved boolean field.

go minimal
Call me dull, but I'm not sure I follow what you're doing here. Could you explain a little bit more so I can understand this? Thanks!
neezer
The line of code I posted does the same exact thing as "has_many :fantasies, :through => :fantasizings" except that it checks your fantasizings table for an is_approved boolean. So User.fantasies lists all fantasies, User.approved_fantasies lists all fantasies that have been approved.
go minimal
Played around with it and I think I got the gist of it. Thanks.
neezer