2012-03-14 28 views
4

我使用戶通過created_attotal_votes到帖子排序:如果控制器爲nil,那麼在控制器中設置默認值爲param屬性?

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(當它爲零時)。

這樣做的最好方法是什麼?

回答

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

+2

小心'|| ='設置默認值。 'params [:my_bool] || = true'將始終爲真,如果沒有定義則爲true。 – CambridgeMike 2015-05-18 23:10:56

相關問題