将 Rails 中的主键更改为字符串 [英] Altering the primary key in Rails to be a string

查看:30
本文介绍了将 Rails 中的主键更改为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个模型,State 和 Acquisition.状态 has_many 收购.我觉得 51 条记录的自动递增整数主键相当愚蠢.所以我将 State 的模型更改为 PK(State 是两个字母的缩写;我没有在任何地方存储实际的州名:

So I've got two models, State and Acquisition. State has_many Acquisitions. I felt like an autoincrementing integer primary key for 51 records was rather silly. So I altered the model for the State to be the PK (State being the two letter abbreviation; I'm not storing the actual state name anywhere:

class State < ActiveRecord::Base  
  self.primary_key = "state"  
  has_many :acquisition_histories  
end

问题是当我创建我的获取模型时,它将外键列 state_id 创建为一个整数.更具体地说,脚本/生成的迁移做了:

The problem is when I created my Acquisition model, it created the foreign key column state_id as an integer. More specifically, the script/generated migration did:

class CreateAcquisitions < ActiveRecord::Migration  
  def self.up  
    create_table :acquisitions do |t|  
      t.date :date  
      t.string :category  
      t.text :notes  
      t.references :state  
      t.timestamps  
    end
  end
end

我假设 t.references 数据类型将其设置为 int.问题是我的 Acquisition 类上的 create 方法试图将状态缩写放入表获取的 state_id 字段中(是的,它在数据库上称为 state_id ,即使它在迁移脚本中说 :state ).该方法不会失败,但它确实在 state_id 字段中放置了一个 0,并且记录进入了以太.

I'm assuming that t.references data type sets it to int. The problem is my create method on my Acquisition class is trying to put a state abbreviation into the state_id field on the table acquisitions (and yes, it's called state_id on the database, even though it says :state in the migration script). The method doesn't fail, but it does put a 0 in the state_id field and the records go into the ether.

推荐答案

Rails 在您不反对默认设置时效果最佳.在你的状态表上有一个整数主键有什么危害?

Rails works best when you don't fight against the defaults. What harm does it do to have an integer primary key on your state table?

除非您坚持使用无法控制的旧架构,否则我建议您坚持使用 Rails 默认值—约定而不是配置,对吗?—并专注于应用程序的重要部分,例如作为 UI 和业务逻辑.

Unless you're stuck with a legacy schema that you have no control over, I'd advise you to stick to the Rails defaults—convention over configuration, right?—and concentrate on the important parts of your app, such as the UI and the business logic.

这篇关于将 Rails 中的主键更改为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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