2012-01-31 77 views
7

我正在使用遠程form_for我的show動作來檢索基於此窗體傳遞的參數的內容。Rails 3:控制器參數默認值

= form_tag modelname_path(@modelname), :id=>"select_content_form", :remote => true, :method => 'get' do    
    = text_field_tag :content_type, params[:content_type], :id=>"select_content_type" 
    = submit_tag "submit", :name => nil, :id=>"select_content_submit" 

我改變控制器中的內容如下:

# Default params to "type1" for initial load 
if params[:content_type] 
    @content_type = params[:content_type]; 
else 
    @content_type = "type1" 
end 

case @content_type 

when "type1" 
    # get the content 
    @model_content = ... 

when "type1" 
    # get the content 
    @model_content = ... 

我的問題是,上述方法是否是唯一的,我們可以爲PARAMS設置默認值或者我們可以做一個更好的方式。這工作,但我想知道這是否是正確的方法。

UPDATE 基礎上的建議之下,我用下面的上了車defaults.merge行錯誤:

defaults = {:content_type=>"type1"} 
params = defaults.merge(params) 
@content_type = params[:content_type] 

回答

9

設置默認選項的一個好方法是讓他們在哈希,並將您的傳入選項合併到它。在下面的代碼中,defaults.merge(params)將覆蓋params散列中的所有值,而不是默認值。

def controller_method 
    defaults = {:content=>"Default Content", :content_type=>"type1"} 
    params = defaults.merge(params) 
    # now any blank params have default values 

    @content_type = params[:content_type] 
    case @content_type 
     when "type1" 
      @model_content = "Type One Content" 
     when "type2" 
      #etc etc etc 
    end 
end 
+1

嗯,有趣。但是,它給了我以下錯誤: *不能將零轉換爲散列* – rgoraya 2012-01-31 08:16:34

+0

它是否會拋出defaults.merge? – 2012-01-31 17:14:15

+0

是的,它確實,修改了帖子以包含代碼。 – rgoraya 2012-01-31 20:12:46

4

如果有一個靜態的類型列表,你可以使它成爲一個下拉框,只是不包括一個空白選項,以便總是選擇一些東西。但是,如果你堅持一個文本框,你可以通過過濾器之前使用清理控制器動作:

class FoosController < ActionController::Base 
    before_filter :set_content_type, :only => [:foo_action] 

    def foo_action 
    ... 
    end 

    protected 

    def set_content_type 
     params[:content_type] ||= "type1" 
    end 
end 
+0

不適用於嵌套參數。例如,如果'params'沒有鍵':outer','params [:outer] [:inner] || ='value''將不起作用。一個可能的(但是詳細的)解決方法是'params [:outer] || = {inner:'value'}; params [:outer] [:inner] || ='value'' – 2016-12-06 22:14:42

+1

噢,這是有效的:'params [:outer] || = {}; params [:outer] [:inner] || ='value'' – 2016-12-06 22:21:17

1

我想加入討論,工作方式設置默認PARAMS:

defaults = { foo: 'a', bar: 'b' } 
params.replace(defaults.merge(params)) 

這避免了通過「params =」分配一個局部變量。