2012-01-31 79 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 =”分配一个局部变量。