2017-08-26 199 views
0

这是一个使用ActiveRecord和Postgres的rails项目。Rails引用自定义唯一标识

嗨我正在使用两个CSV。其中一个是该州所有登记选民的记录。当我创建此表时,我没有使用生成的唯一标识作为索引列,而是使用已分配的状态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作为参考选民表 投票记录的新表/模型添加这是我试过的迁移:

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上的选民,这是一个字母数字字符串?

回答

0

东西线沿线的:

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

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

0

的问题不在于你的迁移,它与你的模型。你需要这个

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

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