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

wjandali picture wjandali · Apr 11, 2013 · Viewed 7.7k times · Source

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!

Answer

Wizard of Ogz picture Wizard of Ogz · Apr 11, 2013

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