Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom ActiveRecord finder invoking named scopes?
    primarykey
    data
    text
    <p>I have a custom finder defined below:</p> <pre><code>class ContainerGateIn &lt;&lt; ActiveRecord::Base ... def self.search(text) result = if text text.split(' ').inject(self) do |result, criteria| case criteria when /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/ result.search_by_date(criteria.to_date) else result.search_by_text(criteria) end end else self end end ... end </code></pre> <p>Where search_by_date and search_by_text are named scopes, and eager is an eager-loading named scope defined as:</p> <pre><code>named_scope :eager, :include =&gt; [{:container_inventory =&gt; {:container =&gt; [:size_type, :grade]}}, :company, :truck, :hauler] </code></pre> <p>The association is setup via a HMT (has_many :through):</p> <pre><code>class ContainerDepot &lt;&lt; ActiveRecord::Base has_many :container_inventories has_many :container_gate_ins, :through =&gt; :container_inventories do end </code></pre> <p>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.</p> <pre><code>ContainerDepot.first.container_gate_ins.eager.search(text) =&gt; ActiveRecord::StatementInvalid: PGError: ERROR: table name "container_inventories" specified more than once </code></pre> <p>I could correct it by copying the whole custom finder as an association extension:</p> <pre><code>class ContainerDepot &lt;&lt; ActiveRecord::Base ... has_many :container_gate_ins, :through =&gt; :container_inventories do def search(text) ... custom finder code from ContainerGateIn ... end end ... end </code></pre> <p>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.</p> <p>Any ideas on how this could be done better?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload