has_one/has_many with dependent destroy but using

2019-08-08 08:53发布

问题:

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