如果控制器为零,则将默认值设置为控制器中的param属性?

时间:2012-03-14 03:51:31

标签: ruby-on-rails

我允许用户按created_attotal_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>

我希望:order_by默认值为total_votes DESC(当它为零时)。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:7)

在控制器中

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

或者

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

Hash#fetch