Stupid Rails rendering

I dont’ understand why it’s not possible to have a conditional
redirection in rendering

respond_to do |format|
format.js {
   render :update do |page|
     page.redirect_to posts_url if @located
     page.replace_html 'error_message', "Error..."
     page << "$('popup_error').popup.show();"
   end
 }
end

raise an error… => Can only render or redirect once per action
what shoudl do if I don"t want to render OR redirect

respond_to do |format|
format.js {
   page.redirect_to posts_url if @located
   render :update do |page|
     page.replace_html 'error_message', "Error..."
     page << "$('popup_error').popup.show();"
   end
 }
end

tfyl

kad

There is no stupid errors here… when you open a render block, you are
rendering a template at this moment… you can’t do other render or
redirect inside… you can have a conditional redirection, but not
inside a render, its pure logic.

Try doing it:

respond_to do |format|
format.js {
if @located
page.redirect_to posts_url
else
render :update do |page|
page.replace_html ‘error_message’, “Error…”
page << “$(‘popup_error’).popup.show();”
end
end
}
end

It’s similar, but not the same.

Kad

You have probably already spotted it, but just in case:

respond_to do |format|
format.js {
if @located
page.redirect_to posts_url
else
render :update do |page|
page.replace_html ‘error_message’, “Error…”
page << “$(‘popup_error’).popup.show();”
end
end
}
end

In the line - page.redirect, page is out of scope.

Will work if you do:

render :update do |page|
if @located
page.redirect_to posts_url
else
page.replace_html ‘error_message’, “Error…”
page << “$(‘popup_error’).popup.show();”
end
end

The reason it needs to be this way is that redirect does not cause the
method to immediately exit, so the other render
statements were getting executed, causing the error.

tonypm

tonypm wrote:

Kad

You have probably already spotted it, but just in case:

The reason it needs to be this way is that redirect does not cause the
method to immediately exit, so the other render
statements were getting executed, causing the error.

tonypm

thanks a lot , yes I spotted it after rewritting the bloc line by
line…
I re-checked all other blocks I had with some begin - rescue -
redirect_to

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs