重构rails3查看activerecord调用

时间:2011-12-14 18:16:05

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

在下面的代码片段中,我在视图中进行了大量的数据库操作。 (.where,以及两个循环)。从视图中重构此代码的最佳方法是什么?

在视图中: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 -%>

1 个答案:

答案 0 :(得分:1)

在Section模型文件中,您可以添加以下方法

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 -%>