2017-02-23 44 views
0

我試圖通過命名外鍵將源端口和目標端口城市(存儲在端口模型中)與作業模型中的記錄相關聯。我已經搜尋了很多這種關係的例子,但我仍然無法通過rails控制檯插入新的Port記錄。作業是在嘗試創建端口記錄之前創建的。以下是該協會的定義:如何編寫與同一表的多個關聯的導軌遷移

class Job < ApplicationRecord 
    has_many :destinations, :class_name => 'Port', :foreign_key => 'destination_id' 
    has_many :origins, :class_name => 'Port', :foreign_key => 'origin_id' 
end 
class Port < ApplicationRecord 
    belongs_to :origin, :class_name => "Job" 
    belongs_to :destination, :class_name => "Job" 
end 

架構(編輯):

create_table "jobs", force: :cascade do |t| 
    t.integer "origin_id" 
    t.integer "destination_id" 
    t.index ["destination_id"], name: "index_jobs_on_destination_id" 
    t.index ["origin_id"], name: "index_jobs_on_origin_id" 
end 
create_table "ports", force: :cascade do |t| 
    t.string "name" 
    t.float "lat" 
    t.float "lon" 
end 

我要找的外鍵在建立這些模型的遷移使用確切的語法。有什麼想法嗎?

+0

你得到一個錯誤或東西做什麼?顯示你用來插入它的代碼也有幫助 – Iceman

回答

0

這聽起來有點像你有其他方式的關係。

假設這是像航運。世界上有很多港口。 船舶/飛機有許多工作。工作是在兩個端口之間。

在這種情況下,

class Job 
    belongs_to :origin, class_name: "Port" 
    belongs_to :destination, class_name: "Port" 
end 

class Port 
    has_many :origin_jobs, class_name: "Job", foreign_key: "origin_id" 
    has_many :destination_jobs, class_name: "Job", foreign_key: "destination_id" 
end 

創建控制檯記錄會像這樣

origin_port = Port.first 
destination_port = Port.second 
Job.create(origin: origin_port, destination: destination_port)