Rails. If Else and Loops
I want to do the following in a partial:
-if (session[:sort] == "up")
- event.days.sort_by{|t| - t.created_at.to_i}.each do |day|
= day.title
= day.etc
-else
- event.days.sort_by{|t| - t.created_at.to_i}.reverse.开发者_JAVA技巧each do |day|
= day.title
= day.etc
But I do not want to repeat
= day.title
= day.etc
I tried:
-if (session[:sort] == "up")
- event.days.sort_by{|t| - t.created_at.to_i}.each do |day|
-else
- event.days.sort_by{|t| - t.created_at.to_i}.reverse.each do |day|
= day.title
= day.etc
But it doesn't work. Maybe I can do it somehow with ternary operator.
Sort the events, only reverse them if the required condition is met, then print them out.
- sorted_events = event.days.sort_by{|t| - t.created_at.to_i}
- sorted_events = sorted_events.reverse unless session[:sort] == "up"
- sorted_events.each do |day|
= day.title
= day.etc
Ideally you would do this sorting in the controller, then just do the display in the view.
It is advisable that you do the sorting logic in the controller and store the output in an instance variable. In the view just do the display thing as:
<% @results.each do |result| %>
<%= result.title %>
<%= result.etc %>
<% end %>
精彩评论