2017-08-26 190 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