Rails 3: default value for Controller parameter

I am using a remote form for my show action to retrieve content based on the parameters passed by this form.

= 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" 

And I modify the contents in the controller as follows:

 # 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 = ... 

My question is whether the above approach is the only one for which we can set default values ​​for parameters, or whether we can do it better. This works, but I would like to know if this is correct.

UPDATE Based on the assumption below, I used the following and got an error in the defaults.merge line:

 defaults = {:content_type=>"type1"} params = defaults.merge(params) @content_type = params[:content_type] 
+7
source share
3 answers

A good way to set default parameters is to hash them and combine incoming parameters. In the code below, defaults.merge(params) will overwrite any values ​​from the default params hash.

 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 
+9
source

If there is a static type list, you can make it a drop-down list and simply not include an empty option so that something is always selected. But if you are stuck in a text box, you can clear the controller action using the before filter:

 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 
+4
source

I wanted to add to this discussion a working way to set default parameters:

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

This avoids assigning a local variable via "params =".

+1
source

All Articles