我有一张用户表和一张礼品表。用户可以为他们的朋友挑选礼物。我正在考虑创建一个表来存储用户ID和礼物ID,以跟踪哪个用户选择了哪个礼物给谁。如何建立这种关系?我认为用户和礼物有HABTM关系。是吗?
答案 0 :(得分:2)
试试这个:
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
现在可以跟随电话:
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
确保您为user_id
表格中的friend_id
,gift_id
,user_gifts
列编制索引。
答案 1 :(得分:0)
嗯,首先,它是一个三向关系,因为你有用户 - &gt;朋友,以及用户 - &gt;礼品。
我会选择has_many:通过并存储朋友的ID。查询会有点尴尬,但它应该有效。