【问题标题】:Ruby - migration reference represented in model [duplicate]Ruby - 模型中表示的迁移参考
【发布时间】:2021-12-28 17:28:11
【问题描述】:

好的,所以我有:

两个实体:gamesapps。他们的关系从appsgames

  • 迁移时如下:add_reference :apps, :games, type: :uuid, foreign_key: true
  • app 模型上是这样的:belongs_to :game
  • game 型号上是这样的:has_many :apps

现在这允许我拥有一个app 并为其分配一个game(在数据库中,它在app 表上显示一个新列game_id)。

我现在要做的是添加一个名为 requested_game 的游戏列。

为此,我添加了以下迁移:add_reference :apps, :requested_game, type: :uuid, foreign_key: { to_table: :games },但现在我不知道如何在模型中显示这种关系。

有什么想法吗?我是否必须创建一个requested_game 模型并将其引用到game 模型?我现在有点迷路了……

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5


    【解决方案1】:

    如果我正确理解您的问题,您希望拥有一个具有以下功能的应用:

    1. 通过game_id链接到应用程序的游戏
    2. requested_game_id 链接到应用程序的请求游戏

    本质上,它是从表 apps 到表 games 的 2 个链接,带有 2 个不同的外键。

    所以在模型App中,可以这样写:

    class App < ActiveRecord::Base
      belongs_to :game, class_name: 'Game', foreign_key: 'game_id'
      belongs_to :requested_game, class_name: 'Game', foreign_key: 'requested_game_id'
    end
    
    # Or with newer versions of Rails
    
    class App < ApplicationRecord
      belongs_to :game, class_name: 'Game', foreign_key: 'game_id'
      belongs_to :requested_game, class_name: 'Game', foreign_key: 'requested_game_id'
    end
    

    在模型Game中,可以这样写:

    class Game < ActiveRecord::Base
      has_many :apps, class_name: 'App', foreign_key: 'game_id'
      has_many :requesting_apps, class_name: 'App', foreign_key: 'requested_game_id'
    end
    
    # Or with newer versions of Rails
    
    class Game < ApplicationRecord
      has_many :apps, class_name: 'App', foreign_key: 'game_id'
      has_many :requesting_apps, class_name: 'App', foreign_key: 'requested_game_id'
    end
    

    【讨论】:

    • 您不需要belongs_to 关联上的foreign_key: 'requested_game_id',因为它是从关联名称而不是类名称推导出来的。并且应该将反向关系命名为更像requesting_apps(因为他们正在执行请求)。
    • 确实,在belongs_to 的情况下,我们不需要指定foreign_key,但我喜欢这种情况下的显式代码。感谢您推荐名称requesting_apps。没错。
    【解决方案2】:

    我认为this Stackoverflow Answer 将多个外键放在一个表上可能会满足您的需求。

    稍微推断一下,听起来您最终可能希望App 模型的实例附加多个方法?例如:

    new_app = App.first
    new_app.game
    => old_game
    new_app.requested_game
    => newly_requested_game
    

    如果这是您想要的,那么如上面的链接中所述,您将希望apps 表上有两个外键,都指向games 表。当然,您必须为表列和game 表中相应的belongs_to 方法提供正确的选项以了解哪个是哪个。

    我认为您不需要创建 RequestedGame 模型,除非您想使用自己的方法和诸如此类的东西创建该模型的实例。因此,如果您想运行 requests_game.app 之类的东西,该模型可能会派上用场。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 2017-07-01
      相关资源
      最近更新 更多