I’m using the following to enable users to sort comments by date (ASC), date (DESC) and vote:
posts_controller.rb:
def show
@post = Post.find(params[:id])
@comments = @post.comments.paginate(:page => params[:page],
:per_page => 5).order(params[:order_by])
@comment = @post.comments.build
end
views/posts/show.html.erb:
<div class="comments-tabs">
<span><%= link_to 'Votes', post_path(@post, :order_by => "total_votes DESC") %></span>
<span><%= link_to 'Date (ASC)', post_path(@post, :order_by => "created_at ASC") %></span>
<span><%= link_to 'Date (DESC)', post_path(@post, :order_by => "created_at DESC") %></span>
</div>
the URL ends up looking like this:
http://localhost:3000/posts/59?order_by=total_votes+DESC
http://localhost:3000/posts/59?order_by=created_at+ASC
http://localhost:3000/posts/59?order_by=created_at+DESC
I would like to create an if statement to add a class to the current tab. For example:
http://localhost:3000/posts/59?order_by=created_at+ASC
<span class="comment-tab"><%= link_to 'Votes', post_path(@post, :order_by => "total_votes DESC") %></span>
<span class="comment-tab current"><%= link_to 'Date (ASC)', post_path(@post, :order_by => "created_at ASC") %></span>
<span class="comment-tab><%= link_to 'Date (DESC)', post_path(@post, :order_by => "created_at DESC") %></span>
You can use the current_page? method to determine whether the user is viewing a certain page and apply an html class based on that.
Here’s an example: