has_one/has_many with dependent destroy but using a different name for the key

岁酱吖の 提交于 2020-01-05 11:59:13

问题


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

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)?

Thanks!


回答1:


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


来源:https://stackoverflow.com/questions/15939799/has-one-has-many-with-dependent-destroy-but-using-a-different-name-for-the-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!