# Which are the right :joins for two models in which one has two belongs\_to the other same model?

**URL:** <https://www.ruby-forum.com/t/which-are-the-right-joins-for-two-models-in-which-one-has-two-belongs-to-the-other-same-model/161974>\
**Category:** Rails\
**Created:** [March 4, 2009, 12:27pm UTC](https://www.ruby-forum.com/t/which-are-the-right-joins-for-two-models-in-which-one-has-two-belongs-to-the-other-same-model/161974 "2009-03-04T12:27:48Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![gabriele](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/76d3ee/32.png) [@gabriele](https://www.ruby-forum.com/u/gabriele)\
**Post date:** [March 4, 2009, 12:27pm UTC](https://www.ruby-forum.com/t/which-are-the-right-joins-for-two-models-in-which-one-has-two-belongs-to-the-other-same-model/161974/1 "2009-03-04T12:27:48Z")

</div>

Hi all,  
here is the main picture (obviously some snips are made):

class JobFile \< ActiveRecord::Base  
belongs\_to :car  
belongs\_to :counterpart\_insurance, :class\_name =\>  
‘Insurance’, :foreign\_key =\> ‘counterpart\_insurance\_id’  
belongs\_to :customer\_insurance, :class\_name =\>  
‘Insurance’, :foreign\_key =\> ‘customer\_insurance\_id’  
end

class Insurance \< ActiveRecord::Base  
has\_many :accident\_counterparts, :class\_name =\>  
‘JobFile’, :foreign\_key =\> 'customer\_insurance\_id"  
has\_many :accident\_customers, :class\_name =\> ‘JobFile’, :foreign\_key  
=\> ‘counterpart\_insurance\_id’  
end

class Customer \< ActiveRecord::Base  
has\_many :cars, :dependent =\> :destroy  
end

class Car \< ActiveRecord::Base  
belongs\_to :customer  
has\_many :job\_files, :dependent =\> :destroy  
end

Now, I would like to have all the customers that have a job\_file that  
deals with an insurance, I’m a bit stuck at writing down the joins  
clause for the named scope:

named\_scope :insurances\_in, lambda { |array| {  
:joins =\> [{:cars =\> {:job\_files =\> :counterpart\_insurance}},  
{:cars =\> {:job\_files =\> :counterpart\_insurance}}],  
:conditions =\> “insurances.name LIKE '%#{array.join(”%")}%’",  
:group =\> “customers.id” }  
}

Is this right?  
Thanks for the help  
G.
