1

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!

2 Answers 2

3

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].

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.