Custom ActiveRecord search invoking named areas?

I have a custom search defined below:

class ContainerGateIn << 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

In those cases where search_by_date and search_by_text are called areas, and impatient is the name-changing area with a look for loading, defined as:

named_scope :eager, :include => [{:container_inventory => {:container => [:size_type, :grade]}}, :company, :truck, :hauler]

Communication is established through 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 that finder is called through an association nested from ContainerDepot, it does not work with 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 fix this by copying the entire user search as an extension of the association:

class ContainerDepot << ActiveRecord::Base
  ...
  has_many :container_gate_ins, :through => :container_inventories do
    def search(text)
      ... custom finder code from ContainerGateIn ...
    end
  end
  ...
end

, , .

, ?

+3
1

named_scope , :

named_scope :eager, lambda {|text| {:conditions=>{:name=>text}, :include => [{:container_inventory => {:container => [:size_type, :grade]}}, :company, :truck, :hauler]}}

.

0

Source: https://habr.com/ru/post/1731151/


All Articles