【问题标题】:How to speed up rendering of a rails_partial with form elements?如何使用表单元素加速 rails_partial 的渲染?
【发布时间】:2018-03-06 14:45:44
【问题描述】:

我有 rails 操作,其中包括以下 HAML 部分:

- @items.each_with_index do |item, i|
  - item_no = 'item' + item.item_no.to_s
  .item
    = form_for item, remote: true, html: { multipart: true, autocomplete: 'off' } do |f|
      = f.hidden_field :parent_id, :value => @parent.id
      = f.hidden_field :image, value: item.image
      ...
      ...
      // 5-6 attributes

    - if @parent.has_item_numbers?
      .serial-number{ class: ('right' if item.item_no.odd?)  }
        = item.item_no

与其parent 关联的items 的数量可能会有很大差异,也可能高达 2000-3000,具体取决于用户。我们还没有限制父母可以拥有的孩子的数量。在我决定 limit: 之前,有没有办法加速 .each_with_index 方法的渲染,因为现在这需要 10 秒才能完成我本地的请求。

有一些关于converting a partial to a method/block 速度的讨论,但我不完全理解。

另外,值得注意的是,同样的部分在 rails 5.0.4 中的表现要好得多,但在 rails 5.1.4 中的表现明显放缓。

【问题讨论】:

    标签: ruby-on-rails caching rendering


    【解决方案1】:

    您通常不应该在视图中进行迭代。相反,您应该使用collection rendering,它将为您执行迭代,并且是known to be faster,此外还允许您实现片段缓存:

    你的看法:

    = render @items, parent: @parent
    

    你的部分(即_item.html.haml):

    - item_no = 'item' + item.item_no.to_s
    .item
      = form_for item, remote: true, html: { multipart: true, autocomplete: 'off' } do |f|
        = f.hidden_field :parent_id, :value => @parent.id
        = f.hidden_field :image, value: item.image
        ...
        ...
        // 5-6 attributes
    
      - if parent.has_item_numbers?
        .serial-number{ class: ('right' if item.item_no.odd?)  }
          = item.item_no
    

    【讨论】:

    • 每次我打开带有大量集合的视图时,这会将 puma 服务器完全挂在我的本地。还在挖……brb。
    • 答案的倒数第三行应该是- if @parent.has_item_numbers?。时间现在在 2.5-3.5 秒的范围内。现在看片段缓存:guides.rubyonrails.org/caching_with_rails.html
    • @marvindanig 我在render 调用中明确传入parent,通常最好不要引用@parent 之类的实例变量。您应该显式地注入您的依赖项。
    • @marvindanig 另请注意:您最初是在做each_with_index,但没有对索引做任何事情,所以我把它省略了。如果您确实需要您的部分索引,它应该以item_iterationapi.rubyonrails.org/v5.1/classes/ActionView/… 的形式提供
    • 我的意思是,在您的部分内容中,您通常不应该依赖 @ 设置的变量。部分用于代码重用,下次您从其他视图渲染该部分时,可能没有@parent,因为该视图没有加载该变量,或者因为它被命名为不同的名称,例如@987654336 @ 在这种情况下,或出于任何其他原因。 @ 变量最好用在顶级视图中,然后可以将命名的局部变量传递给局部变量。
    猜你喜欢
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2012-08-01
    • 2014-04-28
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多