Thoughts, information and reflections about technology

Render layout position in a method

Where you place your render layout in your method matters.

I was debugging a piece of code that definitely was not giving me the results I expected.  I was using a render layout with an alternate style instead of application.html.erb since this was a popup. I did not need the headers, footers and navigation in the popup.  I included the following in my edit method:

render :layout =>  ‘alternate_style’

In order to troubleshoot I initialized a variable called $temp2 before getting to the edit method.  I put the following at the bottom of my form in order to see the variable (yes I could do that with a debugger and get similar results)

$temp2 <%= $temp2 %>

In the method, I set $temp2 to something like ‘tropical.

What I found was that if I put the render before setting the variable, the variable would not change the first time I opened the form. I had to open it again. In other words the following would not work the first time

render :layout => ‘alternate_style’
$temp2 = ‘tropical’

However, if I flipped things around to the following it did work as expected.

$temp2 = ‘tropical’
render :layout => ‘alternate_style’

My edit method now looks something like

def edit
@produced_roll = ProducedRoll.find(roll_id)
$temp2 = ‘tropical’ # TODO remove after debugging
$current_sheet_line = params[:current_sheet_line]
@sheet_line = SheetLine.find(sheet_line_id)
render :layout => ‘alternate_style’
end

Putting the render :layout at the end seems to ensure that the rest of the method is executed before displaying the form.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact me
Archives
Categories
Amazon Disclosure

We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites.