【问题标题】:Why is only 1 query executed in this code involving scopes from the rails-jquery-autocomplete plugin?为什么此代码中只执行 1 个查询,涉及 rails-jquery-autocomplete 插件的范围?
【发布时间】:2011-10-16 01:57:03
【问题描述】:

我正在从 rails jquery 自动完成插件中查看这段代码。在第 12 行中,“items”被设置为一个作用域对象。然后在接下来的几行中,作用域对象似乎被重新分配了几次。

当我运行代码时,似乎只进行了 1 个查询,这是所有范围的总和。(这很好,只是不知道为什么)。这是否意味着作用域对象在执行时会累积作用域直到方法结束?或者 Active Record 只是通过等待收集所有查询来最小化所需的查询数量来优化性能...帮助我理解:) :

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 scope


    【解决方案1】:

    Rails 为您发现的好处的一部分是,当您执行范围的范围(无限)时,Rails 会计算出如何有效地进行查询。在 Ryan 显示范围查询的输出的末尾有一个不错的解释 in this podcast

    【讨论】:

    • 谢谢,自从我开始寻找时,我就发现了“延迟加载”这个词。欣赏它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多