In the below snippet, I'm doing a lot of database manipulation in the view. (The .where, and two each loops). What is the best way to refactor this code out of the view?
In the view: 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 -%>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.