rails 非整数主键 [英] rails non-integer primary key

查看:55
本文介绍了rails 非整数主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张名为 Contracts 的表.它当前的默认主键是 Rails 自动生成的 :id 字段,它是一个整数.我想要一个名为 contractId 的字段,它是一个字符串类型,并将其用作主键.我想知道的是:

I have a table called Contracts. Its current default primary key is the :id field that Rails automatically generates, which is an integer. I want to have a field called contractId that is a string type and use it as a primary key instead. What I want to know is:

  1. 这是最佳实践吗?这样做是否有任何潜在问题?

  1. Is this a best practice? Are there any potential issues with doing this?

我会怎么做

推荐答案

Ruby on Rails (RoR) 喜欢强调约定优于配置的概念.因此,它寻求最小化配置量.因此,如果您希望 contractId 是一种字符串类型,那么您可以在表中添加一个额外的字段,并在您想要的任何地方使用它,并让 Rails 使用 id 作为主键.

Ruby on Rails (RoR) likes to emphasise the concept of convention over configuration. Therefore, it seeks to minimialise the amount of configuration. So if you want contractId that is a string type then you can add one extra field in your table and use it wherever you want and let the Rails use id as primarykey.

生成一个新的迁移文件,命名为ChangePrimaryKey";(你可以给任何名字).

Generate a new migration file name it "ChangePrimaryKey" (You can give any name).

class ChangePrimaryKey < ActiveRecord::Migration
  def up
    remove_column :table, :id # remove existing primary key
    rename_column :table, :udid, :id # rename existing UDID column
    execute "ALTER TABLE table ADD PRIMARY KEY (id);"
  end

  def down
    # Remove the UDID primary key. Note this would differ based on your database
    execute "ALTER TABLE table DROP CONSTRAINT table_pkey;"
    rename_column :table, :id, :udid
    add_column :table, :id, :primary_key
  end
end

如果您要创建新表,您的迁移可能如下所示:

If you are creating a new table, your migration might look like this:

class AddTableWithDifferentPrimaryKey < ActiveRecord:Migration
  def change
    create_table :table, id: false do |t|
      t.string :id, null: false
      # other columns
      t.timestamps
      execute "ALTER TABLE table ADD PRIMARY KEY (id);"
    end
  end
end

注意传递到表中的 id: false 选项 - 这要求 Rails 不要代表您创建主键列.

Notice the id: false options you pass into the table — this asks Rails not to create a primary key column on your behalf.

在模型中,您必须添加以下行以便Rails 以编程方式查找您打算用作主键的列.

In the model, it is essential that you add the following line in order for Rails to programmatically find the column you intend to use as your primary key.

class Table < ActiveRecord::Base
  self.primary_key = :id

  # rest of span
end

我希望你能做剩下的事情.

I hope you can do rest of the things.

如果你想看到 Rails 真正的魔法,不要改变默认 id :)

Don't change default id if you want to see Rails real Magics :)

这篇关于rails 非整数主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆