2017-12-02 4 views
0

データベースをシードしようとしていて、 "ActiveRecord :: RecordInvalid:Validation failed:到着フライトが必要です"というエラーが表示され続けます。私のseed.rbファイルにアソシエーションを作成する私の方法では、私はarrival_airport_idを指定しているので、何が問題なのか分かりません。"フライト"でデータベースにシードする

seeds.rb

Airport.delete_all 
Flight.delete_all 

#Airport seeds 
airports = [ 
["Boston Logan International Airport", "BOS"], 
["Gulfport", "GPT"], 
["Jackson", "JAN"], 
["Charleston", "CRW"] 
] 

airports.each do |full_name, name| 
    Airport.create!(full_name: full_name, name: name) 
end 

    a = Airport.all[0..1] 
    b = Airport.all[2..3] 

    a.each_with_index do |a, index| 
    a.departing_flights.create!(
     arrival_airport_id: b[index] 
    ) 
    end 

空港モデル:

class Airport < ApplicationRecord 
    has_many :departing_flights, class_name: "Flight", foreign_key: "departing_airport_id" 
    has_many :arriving_flights, class_name: "Flight", foreign_key: "arrival_airport_id" 
end 

フライトモデル:

class Flight < ApplicationRecord 
    belongs_to :departing_flight, class_name: "Airport", foreign_key: "departing_airport_id" 
    belongs_to :arriving_flight, class_name: "Airport", foreign_key: "arrival_airport_id" 
end 
+2

私はarrival_airport_idを変更しました:b [index]をarrival_airport_id:b [index] .idに変更しましたが、レールは既にそれを行うと知っていると思いましたか? –

+0

問題が解決したと思われる場合は、質問に回答して他の人に助けてもらうことができます。 –

+0

私は行っていましたが、これが正しいのかどうかはわかりません。私は他の誰かがそれについてどうやって行ったのか分かりました。 –

答えて

0

これはよくある間違いであり、2つの修正があります。

a.each_with_index do |a, index| 
    a.departing_flights.create!(
    arrival_airport_id: b[index] # This line is the problem 
    ) 
end 

idカラムにオブジェクトを割り当てています。 IDをid列に、またはオブジェクトをオブジェクト列に割り当てることができます。

arrival_airport_id: b[index].id 
# or 
arrival_airport: b[index] 

Railsは可能な限り手助けをしますが、適切なオブジェクトタイプを指定する必要があります。

関連する問題