Reno
Reno

Reputation: 2982

Avoiding Nil errors from a form parameter when using a default value for a text_field?

Rails 2.3.5

If below I'm using either a default session value or (with priority) a form parameter, is there a way to write the code below to avoid a nil error?

<%= f.text_field :deliver_to_addr, :size => 100, :maxlength => 100, :value => params[:request][:delivery_to_address] || session[:address]  %>

I worked around the problem by putting a logic block in the controller to come out with a single variable to hold what should be selected (below), but is there a simple way to get around this problem so I don't need a block of code every time I need to use a default value (session[:address] in this case)?

    if !params[:request].blank?
      if !params[:request][:delivery_to_address].blank?
        @delivery_addr_to_select = params[:request][:delivery_to_address]
      else
        @delivery_addr_to_select = session[:address]
      end
    else
      @delivery_addr_to_select = session[:address]
    end

<%= f.text_field :deliver_to_addr, :size => 100, :maxlength => 100, :value => @delivery_addr_to_select %>

Thanks!

Upvotes: 1

Views: 187

Answers (2)

spas
spas

Reputation: 1934

You can use the build in try-method:

@delivery_addr_to_select = params[:request].try(:[], :delivery_to_address) || session[:address]

This will try to invoke the [] hash method with :delivery_to_address if the result is nil it will take the session[:address].

Upvotes: 3

cdesrosiers
cdesrosiers

Reputation: 8892

You might try the gem andand to help shorten the logic to

@delivery_addr_to_select = params[:request].andand[:delivery_to_address] || session[:address]

This works whether or not :request is present because andand will only invoke :delivery_to_address if params[:request] is not nil.

Upvotes: 0

Related Questions