【问题标题】:rails association - has_many vs has_and_belongs_to_manyrails 协会 - has_many vs has_and_belongs_to_many
【发布时间】:2013-11-15 03:15:08
【问题描述】:

我在我认为的基本关联方面遇到了麻烦。

我有一个 Game 模型和一个 Matchset 模型。

在游戏模型中是游戏列表。游戏只在游戏表上列出一次,但它们可以属于多个 Matchset。

matchset.rb -

has_many :games

对于 game.rb 我不确定我会放什么。我不想放置belongs_to,因为它属于许多匹配集,而不仅仅是一个。而且我认为我不想将 has_and_belongs_to_many 放入,因为 matchset 不一定“属于”游戏,但也许我只是看错了。

示例:Matchset 1 包含游戏 1、3 和 5。Matchset 2 包含游戏 2 和 3。Matchset 3 包含游戏 3、4 和 5。

我在 Oracle SQL 方面的背景,在我的脑海中,Matchset 表看起来像这样。

id | game_id 
1  | 1
1  | 3
1  | 5
2  | 2
2  | 3
3  | 3
3  | 4
3  | 5

感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 model-associations


    【解决方案1】:

    这些关系应该适合你:

    class Game < ActiveRecord::Base
      has_many :game_match_set_relations
      has_many :match_sets, through: :game_match_set_relations
    
    class MatchSet < ActiveRecord::Base
      has_many :game_match_set_relations
      has_many :games,  through: :game_match_set_relations
    
    class GameMatchSetRelation < ActiveRecord::Base
      belongs_to :game
      belongs_to :match_set
    
      validates :game_id, presence: true
      validates :match_set_id, presence: true
    

    【讨论】:

    • 我觉得join模型没必要
    • 我认为是,@mechanicalfish:OP 说 The games [...] but they can belong to many Matchsets.
    • 是的,所以has_and_belongs_to_many 没有模型。当然需要连接表本身。
    • 建议在所有情况下都使用连接模型,它为您提供更灵活的关系,您可以在连接模型上添加额外的列,更好的 SQL 查询,更精确的验证等。(请参阅 Rails 样式指南以获得所有优势)
    • 很好的推理,赞成你的答案。谢谢你的链接,我不知道有这样的东西存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2012-03-13
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多