2017-09-25 62 views
1

我有rails动作,包括以下HAML部分:如何加速呈现带有表单元素的rails_partial?

- @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可以大大改变,并且可高达2000-3000以及根据用户的items数目。我们对父母可以拥有的孩子数量没有限制。在我决定limit:之前,有没有办法加速渲染.each_with_index方法,因为现在这需要10秒钟才能在本地完成请求。

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

此外,值得注意的是,这个相同的部分在rails 5.0.4表现更好,但它已经大大减缓与rails 5.1.4

回答

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 
+0

这使得美洲狮服务器完全挂在本地,每次我打开一个大集合的视图。仍在挖掘...... brb。 – marvindanig

+0

答案的第三行应该是' - if @ parent.has_item_numbers?'。时间现在在2.5-3.5秒的范围内。现在看看片段缓存:http://guides.rubyonrails.org/caching_with_rails.html – marvindanig

+1

@marvindanig我明确地在'render'调用中传递'parent',通常最好不要引用像'@ @ parent'。你应该明确注入你的依赖关系。 – meagar