Take the 2-minute tour ×

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?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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

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

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


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

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer


