【问题标题】:How to set foreign key in RailsRails中如何设置外键
【发布时间】:2016-09-13 07:41:57
【问题描述】:

我有一个名为员工的模型。以下是我的迁移文件。

class CreateEmployees < ActiveRecord::Migration
    def change
        create_table :employees, id: false do |t|
            t.string :name
            t.string :password
            t.string :role
            t.primary_key :name
        end
    end
end

现在,我想创建一个名为“teamplayer”的模型,其列为“name”,它需要引用员工模型中的“name”列。和 'tl' 列 它独立于这个模型。以下是我的“teamplayer”迁移文件。

class CreateTeamplayers < ActiveRecord::Migration
    def change
        create_table :teamplayers, :id false do |t|
            t.string :tl
            t.string :name
        end
    end
end

在上述文件中,如何将'name'列引用到模型员工?那么如何在rails中实现外键。

【问题讨论】:

  • 我不会创建没有 PK 的表。

标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord


【解决方案1】:

我想你想研究一下 Active Record 关联 (http://guides.rubyonrails.org/association_basics.html)

我知道您已要求在 name 上创建一个外键,但除非您打算确保该名称是唯一的,否则这可能不是最好的计划(取决于您尝试建模的实际关系 - 一个多/一对一等)。

我很想在employees.id 上设置外键关系。为此,您可以使用has_manybelongs_to 关联。

您可以按如下方式更改您的 teamplayers 迁移:

class CreateTeamplayers < ActiveRecord::Migration
  def change
    create_table :teamplayers, :id false do |t|
        t.belongs_to :employee
        t.string :tl
    end
  end
end

然后在您的 Employee 模型中,您可以添加 has_many 方面:

class Employee < ActiveRecord::Base
  has_many :teamplayers
end

您仍然可以通过简单的加入轻松获取给定 Team Player 记录的员工姓名。

编辑 - 要获取 Employee,您可以执行以下操作,假设 @t 是一个团队玩家实例:

@t.employee.name

(代码未经测试,来自内存,所以......)

【讨论】:

  • 如何在'teamplayer'模型中引用'employee'模型中的'name'列?
  • 查看编辑,但基本上,如果你有一个团队玩家实例,你会得到带有@t.employee.name的员工姓名
【解决方案2】:

你可以在teamplayer模型中做,你只需要在你的迁移中添加索引

class CreateTeamplayers < ActiveRecord::Migration
  def change
    create_table :teamplayers, :id false do |t|
        t.string :tl
        t.string :name
    end
    add_index :teamplayers, :name
  end
end

您可以像这样在员工模型中将名称设置为主键

class Employee < ActiveRecord::Base
  self.primary_key = "name"
  has_many :teamplayers
end

现在可以在 Teamplayer 模型中设置外键

class Teamplayer < ActiveRecord::Base
  belongs_to :employee, foreign_key: 'name'
end

这应该将“姓名”引用到员工模型

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    相关资源
    最近更新 更多