user647345
user647345

Reputation: 143

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

Upvotes: 0

Views: 334

Answers (2)

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

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.

Upvotes: 2

amit_saxena
amit_saxena

Reputation: 7614

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

Upvotes: 2

Related Questions