如何在 Rails 中管理没有 id 的表? [英] How to manage table without id in Rails?

查看:25
本文介绍了如何在 Rails 中管理没有 id 的表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:Person 和 Relation.第二个存储有关两个人之间关系的信息.它有 parent_id 和 child_id 字段,没有 id 字段.我将它与 has_many :through 连接起来,它可以工作.

I have two models: Person and Relation. The second one stores information about relations between two people. It has parent_id and child_id fields and doesn`t have id field. I connected it with has_many :through and it works.

但是:

  1. 即使表中有一些关系(因为没有 id 字段),Relation.find(:all) 也会返回空数组.
  2. 我不知道如何删除关系.

我的模型如下所示:

class Person < ActiveRecord::Base
  has_many :child_relations, 
           :class_name => "Relation", 
           :foreign_key => "parent_id"
  has_many :parent_relations, 
           :class_name => "Relation", 
           :foreign_key => "child_id"

  has_many :children, :through => :child_relations
  has_many :parents, :through => :parent_relations
end

class Relation < ActiveRecord::Base
  belongs_to :parent, :class_name => "Person"
  belongs_to :child, :class_name => "Person"
end

有什么建议吗?

更新:我使用了 has_many :through 因为我还在表中存储了关于关系类型的信息.目前我放弃了,我在我的表中添加了 id 字段(Rails 约定......).但我的问题仍然悬而未决.

UPDATE: I've used has_many :through becouse I also store information about a type of the relation in the table. Currently I gave up and I added id field to my table (Rails convention...). But my question remains open.

推荐答案

has_many :through 取决于连接表中的 id.它使连接表成为一个完整的模型.由于每个对记录的操作都带有一个 id,因此如果没有它,您将无法直接与表交互.当您删除记录时,rails 会生成 sql 以通过其 id 删除记录.如果你有一个作为完整模型的连接表,它必须有一个 id

has_many :through depends on an id in the join table. It makes the join table a whole model. Since every operation with records happens with an id, you wont be able to directly interface with a table without it. When you delete a record rails generates sql to delete the record by its id. If you have a join table that acts as a full model, it must have an id

或者您可以使用 has_and_belongs_to_many,它的工作方式更符合您的预期.删除关系是通过对象的关联而不是直接使用关系模型来删除对象.

Or you can use has_and_belongs_to_many which works more like you expect. The remove a relationship you remove the object via its assocations and not directly with the relationship model.

最好的办法是在连接表中添加一个 ID.这样,将来如果关系模型变得更加复杂,您可以将其作为自己的实体进行跟踪.

Your best bet is to add an ID to the join table. That way in the future if the relationship model becomes more complex you can track it as its own entity.

这篇关于如何在 Rails 中管理没有 id 的表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆