Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Controller params default value

I am using a remote form_for for my show action to retrieve content based on the params 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 alter the content in 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 we can set defaults for params or can we do it in a better manner. This works but I would like to know if this is the right approach.

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

defaults = {:content_type=>"type1"}
params = defaults.merge(params)
@content_type = params[:content_type]
like image 351
rgoraya Avatar asked Jan 31 '12 01:01

rgoraya


3 Answers

A good way of setting default options is to have them in a hash, and merge your incoming options onto it. In the code below, defaults.merge(params) will overwrite any values from the params hash over the default ones.

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
like image 99
Jurassic_C Avatar answered Nov 17 '22 19:11

Jurassic_C


If there is a static list of types you could make it a dropdown box and just don't include a blank option so that something is always selected. But if you're stuck with a textbox you could clean up the controller action by using a 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
like image 27
Tom L Avatar answered Nov 17 '22 17:11

Tom L


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

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

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

like image 23
user2111743 Avatar answered Nov 17 '22 17:11

user2111743