Rails 3:控制器参数默认值

时间:2012-01-31 01:10:46

标签: ruby-on-rails-3 model-view-controller parameters

我正在使用远程form_for进行show动作,以根据此表单传递的参数检索内容。

= 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设置默认值的方法,还是我们能够以更好的方式进行。这有效,但我想知道这是否是正确的方法。

更新 基于下面的建议,我使用了以下内容并在defaults.merge行上出现错误:

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

3 个答案:

答案 0 :(得分:10)

设置默认选项的一种好方法是将它们放在哈希中,并将传入的选项合并到它上面。在下面的代码中,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 :(得分:6)

如果存在静态类型列表,您可以将其设置为下拉框,并且不包含空白选项,以便始终选择某些内容。但是,如果您遇到文本框,则可以使用之前的过滤器来清理控制器操作:

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

答案 2 :(得分:1)

我想在此讨论中添加一种设置默认参数的工作方式:

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

这可以避免通过“params =”分配局部变量。