所以我有两个模型:状态和获取。状态 has_many 收购。我觉得 51 条记录的自动递增整数主键相当愚蠢。因此,我将 State 的模型更改为 PK(State 是两个字母的缩写;我不会在任何地方存储实际的州名称:
class State < ActiveRecord::Base
self.primary_key = "state"
has_many :acquisition_histories
end
问题是当我创建 Acquisition 模型时,它创建了外键列 state_id 作为整数。更具体地说,脚本/生成的迁移做了:
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 方法试图将状态缩写放入表 acquires 的 state_id 字段中(是的,它在数据库上称为 state_id,即使它在迁移脚本中显示为 :state )。该方法不会失败,但它确实在 state_id 字段中放入了 0,并且记录进入了以太坊。
不过,我同意这可能是麻烦多于其价值考虑到在其他地方处理默认值需要付出额外的努力,以防万一actually想做你所要求的:
创建状态迁移:
class CreateStatesTable < ActiveRecord::Migration
def change
create_table :states, id: false do |t|
t.string :state, limit: 2
t.string :name
t.index :state, unique: true
end
end
end
状态模型:
class State < ActiveRecord::Base
self.primary_key = :state
end
请注意,在 Rails 3.2 之前,这是set_primary_key = :state
代替self.primary_key=
see: http://guides.rubyonrails.org/3_2_release_notes.html#active-record-deprecations
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)