2014-07-11 161 views
0

我有兩個型號:更改主鍵和外鍵的ActiveRecord

class Settlement < ActiveRecord::Base 
set_primary_key :settlement_identifier 
has_many :streets 
attr_accessible :city, :name, :service_available, :zip, :country_id,: settlement_identifier 

end 

class Street < ActiveRecord::Base 
belongs_to :settlement, foreign_key: "settlement_identifier" 
attr_accessible :name, :settlement_identifier, :street_identifier 
end 

因爲我做的街道和住區的進口,我需要通過settlement_identifier指向街道,不settlement_id。 當我做

Street.first.settlement #it compare settlement_identifiers from both tables 

但是,當試圖從單結匯的街道,如:

Settlement.first.streets 

它拋出一個錯誤

SELECT "streets".* FROM "streets" WHERE "streets"."settlement_id" = 4263 

ActiveRecord::StatementInvalid: PG::Error: ERROR: column streets.settlement_id does not exist . 

我希望該查詢是:

SELECT "streets".* FROM "streets" WHERE "streets"."settlement_identifier" = 4263 

有什麼幫助嗎?

回答

0

我解決了這個問題。這裏是以下解決方案:

class CreateSettlements < ActiveRecord::Migration 
    def change 
    create_table :settlements, primary_key: :settlement_identifier, id: :false do |t| 
    t.string :name 
    t.string :zip 
    t.string :city 
    t.string :service_available 
    t.integer :country_id 

    t.timestamps 
    end 
    end 
def down 
    drop_table :settlements 
end 
end 

在這裏,我在我的遷移settlement_identifier設置primary_key,並設置ID爲假

而且,我的街遷移:

class CreateStreets < ActiveRecord::Migration 
def change 
    create_table :streets do |t| 
    t.string :name 
    t.integer :settlement_identifier 
    t.string :street_identifier 
    t.timestamps 
    end 
end 
end 

所以,街有參考通過settlement_identifier結算。

結算模式:

class Settlement < ActiveRecord::Base 
has_many :streets, foreign_key: "settlement_identifier" 

attr_accessible :city, :name, :service_available,:settlement_identifier 
end 

街模式:

class Street < ActiveRecord::Base 
    belongs_to :settlement, foreign_key: "settlement_identifier" 

    attr_accessible :name, :settlement_identifier, :street_identifier 

end 

我試圖設置primary_key的結算模式,但沒有奏效。 這對我來說很好。如果有人有其他解決方案,請發表評論或代碼示例。