我正在处理一个Rails似乎不太好用的数据概念 - 一个Route有两个(也就是两个)机场。我终于想出了如何对我的外键进行硬编码以使它们变得合理。
我的models/route.rb
非常简单:
class Route < ActiveRecord::Base
has_one :airport, :foreign_key => 'from_airport_id', :class_name => 'Airport'
has_one :airport, :foreign_key => 'to_airport_id', :class_name => 'Airport'
end
这一切似乎都运转良好,但我似乎无法正确播种。
我的seeds.rb
看起来像这样:
Airport.delete_all
@kpdx = Airport.create(:icao => 'KPDX', :name => 'Portland International Airport', :lat => '45.58869934', :lon => '-122.5979996')
@ksea = Airport.create(:icao => 'KSEA', :name => 'Seattle Tacoma International Airport', :lat => '47.4490013122559', :lon => '-122.30899810791')
Route.delete_all
Route.create(:from_airport_id => @kpdx, :to_airport_id => @ksea, :route => "RIVR6 BTG OLM6")
Route.create(:from_airport_id => @kpdx, :to_airport_id => @ksea, :route => "BTG OLM OLM6")
Route.create(:from_airport_id => Airport.find_by_icao("KSEA"), :to_airport_id => Airport.find_by_icao("KPDX"), :route => "SEATL4 SEA HELNS4")
Route.create(:from_airport_id => Airport.find_by_icao("KSEA"), :to_airport_id => Airport.find_by_icao("KPDX"), :route => "SEA HELNS4")
请注意,我有两种不同的方法可以告诉种子数据从我创建的其中一个机场转到另一个机场。两者都不起作用。当我运行rake db:seed
时,当from_airport_id
表中的ID递增时,所有to_airport_id
和airport
字段都设置为1(我的23&amp; 24)当前运行)。
所以我有两个问题:
谢谢!
答案 0 :(得分:9)
我会更改你的模型,为每个关系指定一个不同的符号:
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
由于启用has_one
可让您通过名称访问该关系(例如route.airport
),因此这些关系必须不同。
要让您的播种工作,请在机场拨打.id
:
Route.create(:from_airport_id => @kpdx.id, :to_airport_id => @ksea.id, :route => "RIVR6 BTG OLM6")
示例:
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">