Rails引用自定义唯一ID

时间:2017-08-26 20:08:58

标签: ruby-on-rails postgresql activerecord database-design

这是一个使用ActiveRecord和Postgres的rails项目。

您好,我正在处理两个CSV。一个是该州所有登记选民的记录。当我创建此表时,我没有使用生成的唯一ID作为索引列,而是使用已分配的状态state_voter_id。选民表的架构:

create_table "voters", id: false, force: :cascade do |t|
 t.string "state_voter_id", null: false
 t.string "county_voter_id"
 t.string "first_name"
 t.string "middle_name"
 t.string "last_name"
 t.string "suffix"
 t.string "birthdate"
 t.string "gender"
 t.string "add_st_num"
 t.string "add_st_name"
 t.string "add_st_type"
 t.string "add_unit_type"
 t.string "add_pre_direction"
 t.string "add_post_direction"
 t.string "add_unit_num"
 t.string "city"
 t.string "state"
 t.string "zip"
 t.string "county"
 t.string "precinct"
 t.string "leg_dist"
 t.string "cong_dist"
 t.string "reg_date"
 t.string "last_vote"
 t.string "status"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.index ["city"], name: "index_voters_on_city"
 t.index ["first_name"], name: "index_voters_on_first_name"
 t.index ["last_name"], name: "index_voters_on_last_name"
 t.index ["state_voter_id"], name: "index_voters_on_state_voter_id", unique: true
 t.index ["zip"], name: "index_voters_on_zip"
end

我知道想要添加一个包含state_voter_id作为对Voter表的引用的新表/模型的投票记录 这是我尝试的迁移:

def change
 create_table :votes do |t|
  t.references :voter, column: :state_voter_id
  t.string :county
  t.string :date

  t.timestamps
end

当我运行迁移时它已迁移,但当我尝试开始播种选民记录时,我收到以下错误:ActiveRecord::UnknownPrimaryKey: Unknown primary key for table voters in model Voter。我还注意到这张桌子的设置非常重要。

如何设置它以便我正确引用state_voter_id上的Voter,这是一个字母数字字符串?

2 个答案:

答案 0 :(得分:0)

有些事情:

class AddPrimaryKeyToVoters < ActiveRecord::Migration
  def change
    change_column :voters, :state_voter_id, :primary_key
  end
end

在你的选民模特中添加 self.primary_key = "state_voter_id"

答案 1 :(得分:0)

问题不在于您的迁移,而是与您的模型有关。你需要这个

class Voter < ApplicationRecord
   self.primary_key = 'state_voter_id'
   ...
end

请注意,假设Rails 5使用新的ApplicationRecord类。如果你正在使用rails 4,那么就像往常一样继承ActiveRecord::Base