has_one / has_many具有依赖的销毁但使用不同的密钥名称

所以我正在看某人的代码,其中包含以下内容(转述):

class user has_one :connection, :dependent => :destroy has_one :second_user, :through => :connection, :class_name => 'User' end class connection belongs_to :user belongs_to :second_user, :class => 'User' end 

如果我有一个连接对象并删除关联的“用户”,它可以被销毁。 但我也希望这样做,如果占用’second_user’字段的用户被破坏,连接就会被破坏。 如何在不浪费太多的情况下完美无缝地完成(希望不需要迁移)?

谢谢!

请注意,单个用户可以与两个连接相关联。 这意味着在User(作为第二个用户)和尚未定义的Connection之间存在另一个关联。 我称之为secondary_connection

 class User has_one :connection, :dependent => :destroy has_one :secondary_connection, :class_name => 'Connection', :foreign_key => :second_user_id, :dependent => :destroy # Inverse of Connection second_user has_one :second_user, :through => :connection, :class_name => 'User' end 
Interesting Posts