改变Rails中的主键是一个字符串 [英] Altering the primary key in Rails to be a string

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

问题描述

所以,我有两个型号,国家和收购。国家的has_many收购。我感觉自己就像一个自动递增的整数主键51的记录是相当愚蠢的。所以我改变了模式,为国家是PK(国家是两个字母的缩写;我不是存储实际状态名称的任意位置:

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。问题是我创造我的采集类方法试图把一个状态缩写成STATE_ID场在桌子上收购(是的,这就是所谓STATE_ID在数据库中,即使它说:在迁移脚本状态​​)。该方法不会失败,但它并把0在STATE_ID字段和记录进入醚。

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的默认值和mdash;约定优于配置,右mdash;并专注于您的应用程序的重要组成部分,这种作为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天全站免登陆