2017-02-23 3 views
0

名前付き外部キーを使用して、起点および宛先ポートの都市(ポート・モデルに格納されている)をジョブ・モデル内のレコードに関連付けることを試みています。私はこのタイプの関係の多くの例を精査しましたが、まだレールコンソール経由で新しいポートレコードを挿入することはできません。ジョブは、ポートレコードを作成する前に作成されます。ここでは協会の定義は以下のとおりです。同じテーブルで複数の関連付けを行うためのレール・マイグレーションの作成方法

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

もう少しお互いに関係があるように聞こえます。

これはShippingのようなものです。世界には多くの港があります。 船/飛行機には多くのジョブがあります。ジョブは2つのポートの間にあります。このシナリオでは

、コンソール内のレコードを作成

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) 
関連する問題