4

I'm enabling users to sort posts by created_at and total_votes:

posts_controller.rb:

@posts = current_user.subscribed_posts.paginate(:page => params[:page],
                                                :per_page => 5,
                                                :order => params[:order_by])

show.html.erb:

  <span class="comment-tab <% if params[:order_by] == 'created_at DESC' %>current-tab<% end %>"><%= link_to 'Date (DESC)', post_path(@post, :order_by => "created_at DESC") %></span>
  <span class="comment-tab <% if params[:order_by] == 'created_at ASC' %>current-tab<% end %>" ><%= link_to 'Date (ASC)', post_path(@post, :order_by => "created_at ASC") %></span>
  <span class="comment-tab <% if params[:order_by] == 'total_votes DESC' or params[:order_by].nil? %>current-tab<% end %>"><%= link_to 'Votes', post_path(@post, :order_by => "total_votes DESC") %></span>

I would like :order_by to have the value of total_votes DESC by default (when it is nil).

What's the best way of doing this?

1 Answer 1

9

In the controller

params[:order_by] ||= "total_votes DESC"

Or

# fetch returns the default value if the key is not present
params.fetch(:order_by, "total_votes DESC")

Hash#fetch

Sign up to request clarification or add additional context in comments.

1 Comment

Be careful with ||= for setting defaults. params[:my_bool] ||= true will always be true, not true iff it's not defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.