HAS_ONE /的has_many与依赖摧毁,但使用不同的名称为重点 [英] has_one/has_many with dependent destroy but using a different name for the key

查看:243
本文介绍了HAS_ONE /的has_many与依赖摧毁,但使用不同的名称为重点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在看别人的code具有以下(转述):

So I'm looking at someone's code which has the following (paraphrased):

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字段被销毁的连接被破坏。我怎么能无缝地实现这个目标pretty没有太多搞乱(希望没有迁移需要)?

If I have a connection object and delete the associated 'user' it can be destroyed fine. But I also want to make it so that if the User occupying the 'second_user' field is destroyed the connection is destroyed. How can I accomplish that pretty seamlessly without messing with too much (hopefully no migrations needed)?

谢谢!

推荐答案

请注意,单个用户可以使用两个连接有关。这意味着,有其中用户之间存在另一个关联(作为第二用户),并连接其尚未定义。我称之为 secondary_connection

Note that a single User can be associated with two connections. That means there is another association which exists between User (as the second user) and Connection which is not yet defined. I'll call it 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

这篇关于HAS_ONE /的has_many与依赖摧毁,但使用不同的名称为重点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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