I”m looking at this code from the rails jquery autocomplete plugin.. in line 12 “items” is set to be a scoped object. Then it seems over the next few lines that scoped object is reassigned several times.
When I run the code it seems only 1 query is being made wwhich is the sum total of all the scopes..(which is great, just not sure why). Does that mean that a scoped object accumulates scopes until the end of the method when it is executed? Or does Active Record just optimize performance by minimizing the number of queries needed by waiting for all the queries to be gathered… help me understand 🙂 :
def get_autocomplete_items(parameters)
model = parameters[:model]
term = parameters[:term]
method = parameters[:method]
options = parameters[:options]
scopes = Array(options[:scopes])
limit = get_autocomplete_limit(options)
order = get_autocomplete_order(method, options, model)
items = model.scoped
scopes.each { |scope| items = items.send(scope) } unless scopes.empty?
items = items.select(get_autocomplete_select_clause(model, method, options)) unless options[:full_model]
items = items.where(get_autocomplete_where_clause(model, term, method, options)).
limit(limit).order(order)
end
It’s part of the niceness that Rails figures out for you, that when you’re doing scopes of scopes of scopes (ad infinitum), that it Rails figures out how to make the query efficiently. There’s a decent explanation in this podcast toward the end where Ryan shows the output of the scope queries.