Skip to content

Instantly share code, notes, and snippets.

@brenoperucchi
Last active August 29, 2015 14:18
Show Gist options
  • Save brenoperucchi/0b587e0e691f9bbb6b7a to your computer and use it in GitHub Desktop.
Save brenoperucchi/0b587e0e691f9bbb6b7a to your computer and use it in GitHub Desktop.
class CostCenter < ActiveRecord::Base
has_ancestry :cache_depth =>true
attr_accessor :external
belongs_to :store
has_many :lines, :through => :costs_ledgers_line, source: :line
has_many :ledgers, :through => :costs_ledgers_line, source: :ledger
validates_presence_of :name
validates :name, uniqueness: { :case_sensitive => false, :allow_blank => true, scope: [:store_id]}
def self.search(query)
return all.map(&:name) if query == "false"
suppliers = where("name like ? AND `cost_centers`.`ancestry_depth` = 1", "%#{query}%").group(:ancestry).collect{|ancestry| ancestry}
end
## Eu faço query `` name like "%#{query}%" ``para descobrir que são objetos e depois disso eu agrupo tudo dessa menira
## ".group(:ancestry).collect{|ancestry| ancestry}" para ter os costcenter roots sem duplicação.
end
class CostCentersController < ApplicationController
before_action :set_costcenter, only: [:show, :edit, :update, :destroy]
before_action :collection
respond_to :html, :xml, :json, :js
def list
query = params[:query]
@collection = current_store.cost_centers.search(query)
respond_to do |wants|
wants.json { render json: CostCenterPresenter.new(@collection, query).to_json }
end
end
end
class CostCenterPresenter
def initialize(object, query)
@object = object
@query = query
end
# results: [
#1# { text: "Western", children: [
#2# { id: "CA", text: "California" },
#2# { id: "AZ", text: "Arizona" }
# ] },
#1# { text: "Eastern", children: [
#2 # { id: "FL", text: "Florida" }
# ] }
# ]
def to_json
{ 'results' => @object.map do |c|
{
'text' => c.root.name,
'children' =>c.root.children.where("name like ? AND `cost_centers`.`ancestry_depth` = 1", "%#{@query}%").map do |child|
## Depois eu monto o json no CostCenterPresenter.rb procurando novamente a partir do root
## os objetos da query do usuário #2#
{
"id" => child.name,
"text" => child.name,
}
end
}
end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment