Rails 3:控制器参数默认值

rgo*_*aya 8 parameters model-view-controller ruby-on-rails-3

我正在使用远程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"
Run Code Online (Sandbox Code Playgroud)

我改变控制器中的内容如下:

# 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 = ...
Run Code Online (Sandbox Code Playgroud)

我的问题是,上述方法是否是我们唯一可以为params设置默认值的方法,还是我们能够以更好的方式进行.这有效,但我想知道这是否是正确的方法.

更新 根据下面的建议,我使用以下内容并在defaults.merge行上出错:

defaults = {:content_type=>"type1"}
params = defaults.merge(params)
@content_type = params[:content_type]
Run Code Online (Sandbox Code Playgroud)

Jur*_*c_C 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
Run Code Online (Sandbox Code Playgroud)

  • 嗯,有趣.但是,它给我以下错误:*无法将nil转换为Hash* (2认同)
  • 对我有用的是:params [:arg] || ="default" (2认同)

Tom*_*m L 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
Run Code Online (Sandbox Code Playgroud)