Rails 关系建模

发布于 2024-09-19 11:15:39 字数 112 浏览 7 评论 0原文

我有一个用户表和一个礼物表。用户可以为朋友挑选礼物。我正在考虑创建一个表来存储用户 ID 和礼物 ID,以跟踪哪个用户为谁挑选了哪个礼物。如何建模这种关系?我认为用户和礼物之间存在 HABTM 关系。是这样吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

峩卟喜欢 2024-09-26 11:15:39

试试这个:

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_gifts 中对 user_idfriend_idgift_id 列建立索引桌子。

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.

一身骄傲 2024-09-26 11:15:39

好吧,首先它是一个三向关系,因为你有 Users -> 。朋友,还有用户->礼物。

我会使用 has_many :through 并将朋友的 ID 存储在那里。查询起来会有点尴尬,但应该可以。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文