# Custom ActiveRecord finder invoking named scopes?

**URL:** <https://www.ruby-forum.com/t/custom-activerecord-finder-invoking-named-scopes/182819>\
**Category:** Rails\
**Created:** [February 3, 2010, 8:29am UTC](https://www.ruby-forum.com/t/custom-activerecord-finder-invoking-named-scopes/182819 "2010-02-03T08:29:02Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Erol\_F](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/ce73a5/32.png) [@Erol\_F](https://www.ruby-forum.com/u/Erol_F)\
**Post date:** [February 3, 2010, 8:29am UTC](https://www.ruby-forum.com/t/custom-activerecord-finder-invoking-named-scopes/182819/1 "2010-02-03T08:29:02Z")

</div>

I have a custom finder defined here: [http://www.pastie.org/807187](http://www.pastie.org/807187)

Where search\_by\_date and search\_by\_text are named scopes, and eager is  
an eager-loading named scope defined as:

named\_scope :eager, :include =\> [{:container\_inventory =\> {:container  
=\> [:size\_type, :grade]}}, :company, :truck, :hauler]

The association is setup via a HMT (has\_many :through):

class ContainerDepot \<\< ActiveRecord::Base  
has\_many :container\_inventories  
has\_many :container\_gate\_ins, :through =\> :container\_inventories do  
end

The problem is if the finder is invoked via association nesting from  
ContainerDepot, it fails with an ActiveRecord::Statement::Invalid,  
saying that the table has been specified more than once.

ContainerDepot.first.container\_gate\_ins.eager.search(text)  
=\> ActiveRecord::StatementInvalid: PGError: ERROR: table name  
“container\_inventories” specified more than once

I could correct it by copying the whole custom finder as an  
association extension:

class ContainerDepot \<\< ActiveRecord::Base  
…  
has\_many :container\_gate\_ins, :through =\> :container\_inventories do  
def search(text)  
… custom finder code from ContainerGateIn …  
end  
end  
…  
end

it is not very DRY though and introduces a very unnecessary and  
potentially problematic redundancy, as the custom finder will have to  
be changed from time to time to accomodate additional search logic.

Any ideas on how this could be done better?
