Local variable undefined in respond_to json block-Collection of common programming errors

I have the following block of code that renders a form. The form will have it’s “action” set depending on the format requested.

respond_to do |format|
  format.html { render "new", :locals => {:format => "html"} }
  format.json do
    render 'new.html', {
      :locals       => {:format => "json"},
      :content_type => 'text/html',
      :layout       => false
    } 
  end
end

The problem is with :locals => {:format => "json"}. The format.html block works fine, but the form rendered by format.json has the @format variable defined but blank. Where have I gone wrong?

  1. Local variables are not set as instance variables when passed to render with the locals option. The format variable should be available as just that, a local variable (format vs @format)

    The reason you’re seeing @format as being defined is because that is how Ruby works. When instance variables are accessed before they are assigned to a value, they will return nil:

    @format # => nil
    @format = 'value'
    @format # => 'value'
    

Originally posted 2013-11-09 23:18:23.