Rails 3: Multiple has_one associations & seeding

前端 未结 1 1946
慢半拍i
慢半拍i 2021-02-10 21:05

I\'m working with a data concept that Rails doesn\'t seem to do great with - a Route has two (and only two) Airports. I finally figured out how to hard-code my foreign keys so t

相关标签:
1条回答
  • 2021-02-10 21:47

    I would change your model to specify a different symbol for each relationship:

    class Route < ActiveRecord::Base
      has_one :from_airport, :foreign_key => 'from_airport_id', :class_name => 'Airport'
      has_one :to_airport, :foreign_key => 'to_airport_id', :class_name => 'Airport'
    end
    

    Since enabling a has_one lets you access that relationship through the name (e.g. route.airport), these need to be different.

    To get your seeding to work, call .id on the airport:

    Route.create(:from_airport_id => @kpdx.id, :to_airport_id => @ksea.id, :route => "RIVR6 BTG OLM6")
    

    Example:

    ruby-1.9.2-p136 :001 > a = Airport.create(:icao => 'KPDX', :name => 'Portland International Airport')
     => #<Airport id: 1, icao: "KPDX", name: "Portland International Airport", created_at: "2011-03-01 02:44:42", updated_at: "2011-03-01 02:44:42">
    ruby-1.9.2-p136 :002 > b = Airport.create(:icao => 'ABCD', :name => 'Another Airport')
     => #<Airport id: 2, icao: "ABCD", name: "Another Airport", created_at: "2011-03-01 02:46:22", updated_at: "2011-03-01 02:46:22">
    ruby-1.9.2-p136 :003 > r = Route.create(:to_airport_id => a.id, :from_airport_id => b.id)
     => #<Route id: 3, from_airport_id: 2, to_airport_id: 1, route: nil, created_at: "2011-03-01 02:46:36", updated_at: "2011-03-01 02:46:36">
    
    0 讨论(0)
提交回复
热议问题