【问题标题】:Multiple relationships to the same models与同一模型的多个关系
【发布时间】:2012-08-09 05:00:56
【问题描述】:

我无法找出最好的方法来做到这一点。我有一个用户模型和一个锦标赛模型,我在这两个模型之间建立了一个 has_many :through 关系,称为“followed_tournaments”,以便用户可以关注锦标赛。因此,我已经在 User 模型中有一个 has_many :tournaments ,在 Tournament 模型中有一个 has_many :users ,这样一个锦标赛就有很多粉丝,一个用户可以关注很多锦标赛。

我想建立另一个 habtm 或 has_many :through 关系,这样用户就可以被视为锦标赛的“贡献者”——与我已经建立的关系完全不同。我希望锦标赛有任意数量的贡献者,并且用户可以为许多锦标赛做出贡献。

实现这一点的最佳方法是什么?

【问题讨论】:

  • 也许你可以把它放在 FollowedTournament 模型上。也许一些布尔属性命名为贡献。

标签: ruby-on-rails


【解决方案1】:

使用sourceclass_name

class Tournament < ActiveRecord::Base
  has_many :users # ... whatever

  has_many :contributions

  # using class_name
  has_many :contributors, :through => :contributions

  # using source
  has_many :contributors, :through => :contributions, :source => :user
end

class Contribution < ActiveRecord::Base
  belongs_to :tournament

  # using class_name
  belongs_to :contributor, :class_name => 'User'

  # using source
  belongs_to :user
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 2023-03-07
    相关资源
    最近更新 更多