优化搜索RoR

时间:2015-05-09 22:26:26

标签: ruby-on-rails postgresql ruby-on-rails-4 search optimization

我正在使用此搜索构建一个RoR(rails 4)项目,并在带有bootstrap 3样式的表中显示。

  1. 我的下一个代码工作但是太慢了。我希望这可以优化。
  2. 有一种方法可以在页面中间显示加载吗?
  3. 我在RoR中很新,我的英语不好。对此我很抱歉。 请帮我!并感谢你的一切!

    <div class="panel panel-primary">
      <div class="panel-body">
        <table class="table table-striped table-bordered table-hover">
          <thead>
            <tr>
              <th>Grado</th>
              <% meses = ((@cargo_total_grado.fecha_inicio)..@cargo_total_grado.fecha_final).map {|d| [d.strftime('%b'), d.year]}.uniq %> 
              <% meses.each do |m| %> 
              <th> <%= m.first + " " + m.second.to_s %> </th>
              <% end %> 
              <th>Total</th>
            </tr>
          </thead>
          <tbody>      
            <% @cursos.each do |curso| %>
            <% alumnos = Alumno.select("id").where(:id => curso.alumno_ids) %>
            <tr>
              <td><small><%= curso.id_curso %></small></td>
              <% total = 0 %>
              <% meses.each do |m| %> 
              <% inicio = (m.second.to_s + m.first.to_s + "-01").to_date %>
              <% final = inicio.next_month %>
              <% mes = alumnos.map { |e| e.planes.map {|r| r.cargos.where("fecha_cargo >= ? AND fecha_cargo < ?", inicio, final).sum(:monto)}.sum }.sum %>
              <% total += mes %>
              <td><small> <%= number_to_currency(mes) %> </small></td>
              <% end %> 
              <th><small><%= number_to_currency(total) %></small></th>
            </tr>
            <% end %>
            <tr>
              <th></th>
              <% totales = 0 %>
              <% meses.each do |m| %> 
              <% inicio = (m.second.to_s + m.first.to_s + "-01").to_date %>
              <% final = inicio.next_month %>
              <% mes_total = @cursos.map { |c| c.alumnos.map { |e| e.planes.map {|r| r.cargos.where("fecha_cargo >= ? AND fecha_cargo < ?", inicio, final).sum(:monto)}.sum }.sum }.sum %>
              <% totales += mes_total %>
              <th><small> <%= number_to_currency(mes_total) %> </small></th>
              <% end %> 
              <th><small><%= number_to_currency(totales) %></small></th>
            </tr>
          </tbody>
        </table>
      </br>
    </div>
    

2 个答案:

答案 0 :(得分:3)

所以你的问题是你有太多的SQL调用。 Rails需要在数据库中查询每个导致速度减慢的数据库。

您应该查看Eager Loading以解决此问题,通常称为 N + 1查询问题

  

Active Record允许您事先指定要加载的所有关联。这可以通过指定Model.find调用的includes方法来实现。使用includes,Active Record可确保使用尽可能少的查询加载所有指定的关联。

例如,您似乎正在将多个课程加载到@cursos对象中,并从中加载多个Alumno对象,然后加载那些加载Cargo个对象。这将导致多次调用数据库。在您的模型中,您可以执行以下操作:

@cursos = Curso.includes(alumnos: [:cargos]).all

对于答案的第二部分,是否可以显示加载动画:
是的,你可以,但是你必须使用AJAX调用才能从你创建的其他路由中加载返回所需信息的信息。它不是太复杂,但确实给应用程序增加了一些复杂性。 Take a look at this if you're interested

P.S。 Parece quehablasespañol? Si hay algo que no entiendespuedoexplicártelopochat,solo me avisas cuando tengas tiempo。

答案 1 :(得分:0)

为了获得更多优化结果,您可以使用弹性搜索。

相关问题