Rails 模型关系:有一个但也属于多个

发布于 2024-08-28 09:10:13 字数 440 浏览 4 评论 0原文

我有两个模型,Modela 和 Modelb。

Modela 只能拥有一个 Modelb,但 Modelb 可以是多个 Modela 的一部分。

我现在所拥有的是

class Modela < ActiveRecord::Base
  has_one :modelb
end

class Modelb < ActiveRecord::Base
  belongs_to :modela, :foreign_key => "modela_id" #might not make sense?
end

不太确定我在那里做的整个 :foreign_key 事情,但它是我停止时的位置。由于我试图允许 Modelb 成为许多 Modela 的一部分,因此我不想将 modela_id 字段添加到 Modelb 表中。

最好的方法是什么?

I have two Models, Modela and Modelb.

Modela can only own one Modelb, but Modelb can be a part of many Modela's.

What I have right now is

class Modela < ActiveRecord::Base
  has_one :modelb
end

class Modelb < ActiveRecord::Base
  belongs_to :modela, :foreign_key => "modela_id" #might not make sense?
end

Not too sure about the whole :foreign_key thing I was doing there, but it was where it was when I left off. As I am trying to allow Modelb to be part of many Modela's, I don't want to add a modela_id field to the Modelb table.

What is the best way to do this?

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

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

发布评论

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

评论(1

晚风撩人 2024-09-04 09:10:13

它应该是:

class Modela
  belongs_to :modelb
end

class Modelb
  has_many :modela
end

并且 modelas 表应该包含 modelb_id 列。

It should be:

class Modela
  belongs_to :modelb
end

class Modelb
  has_many :modela
end

And modelas table should contain modelb_id column.

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