gpt4 book ai didi

ruby-on-rails - Rails 两个模型之间的多个关联

转载 作者:行者123 更新时间:2023-12-04 08:56:03 25 4
gpt4 key购买 nike

我在 Rails 3 应用程序中有 Flight、Person 和 Glider 模型。我已经定义了自定义关系,因为我需要多个引用来自航类表的 Person 的外键。协会工作,但只有一种方式。

class Flight < ActiveRecord::Base
belongs_to :pilot, :class_name => "Person"
belongs_to :instructor, :class_name => "Person"
belongs_to :towplane_pilot, :class_name => "Person"
belongs_to :airplane_instructor, :class_name => "Person"

belongs_to :glider
belongs_to :rep_glider, :class_name => "Glider"

belongs_to :departure_airfield, :class_name => "Airfield"
belongs_to :arrival_airfield, :class_name => "Airfield"

end

class Glider < Aircraft
has_many :flights
has_many :replaced_flights, :foreign_key => "rep_glider_id", :class_name => "Flight"
end

class Person < ActiveRecord::Base
has_many :flights, :foreign_key => "pilot_id", :class_name => "Flight"
has_many :instructed_flights, :foreign_key => "instructor_id", :class_name => "Flight"
has_many :towed_flights, :foreign_key => "towplane_pilot_id", :class_name => "Flight"
has_many :instructed_towing_flights, :foreign_key => "airplane_instructor_id", :class_name => "Flight"
end


####What works#####
Flight.first.glider
Flight.first.rep_glider
Flight.first.pilot
Flight.first.instructor
Flight.first.towplane_pilot
Flight.first.airplane_instructor

Glider.first.flights
Glider.first.replaced_flights

####What doesn't work#### ----> NoMEthodError 'match'
Person.first.flights
Person.first.instructed_flights
Person.first.towed_flights.
Person.first.instructed_towing_flights

我快到了,但我不明白如何 Glider.first.flightsPerson.first.flights 时确实有效没有。

更新:与“机场”的关联有效......所以我不知道为什么它不适用于“人”
class Airfield < ActiveRecord::Base
has_many :takeoff_flights, :foreign_key => "departure_airfield_id", :class_name => "Flight"
has_many :grounded_flights, :foreign_key => "arrival_airfield_id", :class_name => "Flight"
end

###Works Correctly

Airfield.first.takeoff_flights
Airfield.first.grounded_flights

Flight.first.departure_airfield
Flight.first.arrival_airfield

最佳答案

你们的飞行员有类型吗?像pilot_type 列?我也刚刚开始阅读这些类型的模式,幸运的是它仍然有点新鲜(希望如此。如果我错了忍者,请纠正我!:))

您需要这里讨论的多态模式:

http://asciicasts.com/episodes/154-polymorphic-association

关于ruby-on-rails - Rails 两个模型之间的多个关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5554590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com