与同一事物的多种关系 Rails

发布于 2024-12-14 23:17:03 字数 431 浏览 2 评论 0原文

我对 Rails 很陌生,所以请原谅我的知识有限。

如果我想创建一个 Web 应用程序供飞行员记录航班,我可能有以下模型...

class Flight < ActiveRecord::Base
    belongs_to :plane
    belongs_to :pilot
end

class Plane < ActiveRecord::Base
    has_many :flights
end

class Pilot < ActiveRecord::Base
    has_many :flights
end

但是,如果我希望我的航班类别与机场类别相关两次,一次与始发机场相关,另一次与始发机场相关目的地机场,我该怎么做?

另外,我将如何在机场方面建立关系?...

对此的任何建议将不胜感激。

I'm very new to rails so please forgive my limited knowledge.

If I wanted to create a web app for pilots to log flights, I might have the following models...

class Flight < ActiveRecord::Base
    belongs_to :plane
    belongs_to :pilot
end

class Plane < ActiveRecord::Base
    has_many :flights
end

class Pilot < ActiveRecord::Base
    has_many :flights
end

However, if I wanted my Flight class to be related to an Airport class twice, one for the origin airport, and again for the destination airport, how would I do that?

Also how would I then set the relationship up on the airport side?...

Any advice on this would be much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白芷 2024-12-21 23:17:03

您必须设置 class_name 和foreign_key 选项。你可以尝试这样的事情:

belongs_to :origin_airport, :class_name => "Airport", :foreign_key => "origin_airport_id"
belongs_to :destination_airport, :class_name => "Airport", :foreign_key => "destination_airport_id"

显然,命名取决于你。 文档中有一个示例。

You have to set the class_name and the foreign_key options. You could try something like:

belongs_to :origin_airport, :class_name => "Airport", :foreign_key => "origin_airport_id"
belongs_to :destination_airport, :class_name => "Airport", :foreign_key => "destination_airport_id"

Obviously, naming is up to you. There is an example in docs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文