【问题标题】:Refactoring rails3 view activerecord call重构 rails3 查看 activerecord 调用
【发布时间】:2011-12-14 18:16:05
【问题描述】:

在下面的 sn-p 中,我在视图中进行了大量的数据库操作。 (.where 和两个 each 循环)。将此代码重构到视图之外的最佳方法是什么?

在视图中:index.html.erb

<%- @lesson.sections.each do |section| -%>
          <%- section_correlations = section.correlations.where(:grade => 4) %>
          <%- unless section_correlations.blank? -%>
              <h3><%= section.full_title %></h3>
                <%- section_correlations.each do |correlation| -%>
                      <%= correlation.description %>
                <%- end -%>
          <%- end -%>
<%- end -%>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord refactoring where


    【解决方案1】:

    在截面模型文件中你可以添加以下方法

    def get_correlation_descriptions(grade)
      correlations.where(:grade => grade).map { |c| c.description }
    end
    

    在您的课程模型中:

    def sections_with_correlation_names(grade)
      section_data = []
      sections.each do |s|
        correlation_names = s.get_correlation_descriptions(grade)
        unless correlation_names.blank?
          section_data << { :name => s.full_title, :correlations => correlation_names } 
        end
      end
      section_data
    end
    

    那么在你看来:

    <%- @lesson.sections_with_correlation_names(4).each do |section| -%>
      <h3><%= section[:name] %></h3>
      <%= section[:correlations].join("\n") %>
    <%- end -%>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多