【问题标题】:Records in join table destroyed automatically in HABTM association?连接表中的记录在 HABTM 关联中自动销毁?
【发布时间】:2011-02-16 17:04:21
【问题描述】:

假设我有一个关联,其中用户拥有并属于许多角色。当我销毁用户时,连接表中的记录是否也会自动删除?还是我需要使用 :dependent => :destroy?如果我销毁角色会怎样?

class User < ActiveRecord::Base
   has_and_belong_to_many :roles # need to use :dependent => :destroy to remove join record?
end

class Role < ActiveRecord::Base
   has_and_belong_to_many :users # need to use :dependent => :destroy to remove join record?
end

【问题讨论】:

    标签: ruby-on-rails join has-and-belongs-to-many destroy


    【解决方案1】:

    连接表条目已删除,但角色或用户未删除。您不能在 has_and_belongs_to_many 中添加从属破坏子句,但如果您愿意,可以将它们添加到连接模型中的关系中。例如,要在删除关联的连接表条目时销毁角色,您可以执行以下操作:

    class RolesUser < ActiveRecord::Base
      belongs_to :role, :dependent => :destroy
      belongs_to :user
    end
    

    【讨论】:

    • 我认为 HABTM 的要点之一是没有中间模型。因此,除非存在 RolesUsers 模型,否则这是行不通的。
    • HABTM 需要一个中间模型/表,否则关系不能存在于关系数据库中。对于@keruilin 试图完成的任务,他需要附加到他现有的 RolesUser 模型或创建它。
    • 澄清一下:HABTM 需要中间 table,但不需要额外模型。如果您需要中间模型中的额外控件或字段,您将使用 has_many/through
    • 阅读this excellent post by shteef 了解有关连接表中其他属性的更多信息。
    【解决方案2】:

    确认 - 当您删除用户或角色时,连接表中与该用户/角色的所有记录也将被删除

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2015-04-25
      相关资源
      最近更新 更多