简体   繁体   English

重构rails3查看activerecord调用

[英]Refactoring rails3 view activerecord call

In the below snippet, I'm doing a lot of database manipulation in the view. 在下面的代码段中,我在视图中进行了很多数据库操作。 (The .where, and two each loops). (.where,每个循环两个)。 What is the best way to refactor this code out of the view? 在视图之外重构此代码的最佳方法是什么?

In the view: index.html.erb 在视图中: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 -%>

in the Section model file you could add the following method 在截面模型文件中,您可以添加以下方法

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

and in your lesson model: 在您的课程模型中:

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

then in your view: 然后在您看来:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM