Rails 模型,属于很多
我很难弄清楚如何将我的一个模型与另一个模型的多个关联起来。
现在,我有:
class ModelA < ActiveRecord::Base
has_many :model_b
end
class ModelB < ActiveRecord::Base
belongs_to :model_a
end
但是... ModelB 不仅需要属于 ModelA 的一个实例,而且可能属于三个实例。我知道有一个 has_many :through,但我不确定在这种情况下它会如何工作。 ModelA 的每个实例将始终具有 ModelB 的三个实例。但如前所述,ModelB 可以属于多个 ModelA 实例。
I'm having a hard time figuring out how to association one of my models with multiple of another.
As it is now, I have:
class ModelA < ActiveRecord::Base
has_many :model_b
end
class ModelB < ActiveRecord::Base
belongs_to :model_a
end
However... ModelB needs to belong to not only one instance of ModelA, but possibly three. I know there is a has_many :through, but I'm not sure how it would work in this case. EVERY instance of ModelA will always have exactly three instances of ModelB. But as said before, ModelB can belong to more than just one instance of ModelA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rails 中的多对多关系不使用
belongs_to
。相反,您想使用几个选项之一。第一个是has_and_belongs_to_many
:您需要在数据库中添加一个额外的联接表,并进行如下迁移:
您可以看到联接表的名称是其他两个表的组合名称。这些表必须按上面的字母顺序排列,并且
:id =>; false
需要在那里,因为我们不希望该表上有主键。它将破坏 Rails 关联。如果您需要存储有关关系本身的信息,还有另一种更复杂的方法,称为
has_many :through
。我写了整篇文章,详细介绍了如何执行这两种方法以及何时使用每种方法:Rails 中的基本多对多关联
我希望这有帮助,如果您有任何其他问题,请联系我!
Many-to-many relationships in rails don't use
belongs_to
. Instead, you want to use one of a couple options. The first ishas_and_belongs_to_many
:And you'll need to add an extra join table in your database, with a migration like this:
You can see that the join table's name is the combination of the two other tables' names. The tables must be mentioned in alphabetical order as above, and the
:id => false
needs to be there, since we don't want a primary key on this table. It will break the rails association.There's also another, more complex method known as
has_many :through
if you need to store info about the relationship itself. I've written a whole article detailing how to do both methods, and when to use each:Basic many-to-many Associations in Rails
I hope this helps, and contact me if you have any other questions!
这就是 @Jaime Bellmyer 使用的,
我建议使用它,
如果您使用它,您将拥有一个连接模型,它可以让您更好地控制处理类别和项目。但是使用 @Jaime 的建议,您将只有一个连接表,而不是一个模型,这将不受控制。
This is what @Jaime Bellmyer used
I would recommend using this
If you use this you will have a join model which will give you more control over handling Category and Item. But using what @Jaime suggested you will have only a join table and not a model, which will not be under control.