views:

33

answers:

2

I have a users table and a gifts table. Users can pick gifts for their friends. I am thinking of creating a table to store user id and gift id to track which user picked which gift for whom. How to model this relation? I think users and gifts have a HABTM relation. Is that right?

A: 

Well, first of all it's a three-way relation, as you have Users -> Friends, as well as Users -> Gifts.

I would go with a has_many :through and store there the friend's ID. It will be a bit awkward to query, but it should work.

Srdjan Pejic
+1  A: 

Try this:

class User < ActiveRecord::Base
  has_many :user_gifts
  has_many :gifts, :through => :user_gifts  

  has_many :rcvd_user_gifts, :class_name =>"UserGift", :foreign_key => :friend_id
  has_many :rcvd_gifts, :through => :rcvd_user_gifts, :source => :gift
end

class UserGift < ActiveRecord::Base
  # user_id
  # friend_id
  # gift_id

  belongs_to :user
  belongs_to :friend, :class_name => "User"
  belongs_to :gift

end

class Gift < ActiveRecord::Base
  has_many :user_gifts
  has_many :senders, :through => :user_gifts, :source => :user
  has_many :receivers, :through => :user_gifts, :source => :friend
end

Now following calls are possible:

user.gifts      # Gifts given by a user:
user.rcvd_gifts # Gifts received by a user:
gift.senders    # Users sending a gift
gift.receivers  # Users receiving a gift

Make sure you index the user_id, friend_id, gift_id columns in user_gifts table.

KandadaBoggu