1

我正在开发一个必须在主页上显示产品列表的 Web 应用程序。为此,我有一个 ProductsController:

     class ProductsController < ApplicationController
       include ProductsHelper
       def index
        @products = Product.last(6).reverse
       end
     end  

以及相应的视图 index.haml:

    .main-container.col3-layout
      .main
        .col-wrapper
           .col-main
            .box.best-selling
              %h3 Latest Products
              %table{:border => "0", :cellspacing => "0"}
                %tbody
                  - @products.each_slice(2) do |slice|
                    %tr
                      - slice.each do |product|
                        %td
                          %a{:href => product_path(:id => product.id)}
                            = product.title
                            %img.product-img{:alt => "", :src => product.image.path + product.image.filename, :width => "95"}/
                          .product-description
                            %p
                              %a{:href => "#"}
                            %p
                              See all from
                              %a{:href => category_path(:id => product.category.id)}
                                = product.category.label
        =render "layouts/sidebar_left"
        =render "layouts/sidebar_right"

为了提高效率,我想使用助手,但我不知道如果不在 products_helper.rb 文件中编写 HAML 代码,我怎么能做到这一点。

关于如何实现这一点有什么想法吗?

4

1 回答 1

1

以下一些用于优化,另一些用于清理。

  1. 急切地加载您的关联以减少数据库查询的数量。

    @products = Product.includes(:category).all
    @products.each do |product|
      puts product.category.name
    end
    
  2. 创建三列布局模板。让这包括你的视图模板中除了那些里面的所有东西.col-main,并yield在你的布局模板里面移动.col-main。从视图模板中删除特定于布局的 HAML。

  3. 使用image_taglink_to查看助手。这可能比您自己定义标签要慢,但同样已知 HAML 比 ERB 慢

    %a{:href => '/hyperlink/url'}
      = "hyperlink text"
    
    = link_to 'hyperlink text', '/hyperlink/url'
    
  4. 利用路径生成助手。

    = category_path(:id => @category.id)
    = category_path(@category)
    
  5. 将产品表格单元格的标记和代码移动到部分视图。

于 2013-10-29T18:00:56.847 回答