Rails 模型关系:有一个但也属于多个
我有两个模型,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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它应该是:
并且 modelas 表应该包含
modelb_id
列。It should be:
And modelas table should contain
modelb_id
column.