Paul S.
Paul S.

Reputation: 4492

Rails: redirecting from controller

In my Rails 3.2 project, in my controller, I have a show_html function. If it can find a site with a particular URL in the database, it will pass that on to the view. Otherwise, I want it to redirect to http://www.google.com

def show_html
  site_list = Site.where(:url => params[:url])
  if site_list.length > 0
    site = site_list.first

  else
    redirect_to "http://www.google.com"
  end

  @html = site.html
  render "show_html.html.erb"

end

When I tested it and site_list.length > 0, it works. But when site_length_list = 0, it gives an error undefined method 'html' for nil:NilClass. Why doesn't it go into the else statement and render google.com?

Upvotes: 0

Views: 1028

Answers (3)

oldergod
oldergod

Reputation: 15010

If you don't get into the if, your site will be nil.
And if you don't set return with the redirect, the function will just go all the way down, even if you don't have the nil error, you will probably get an other one with a redirect + a render.

A clean way to define your function

def show_html
  site_list = Site.where(:url => params[:url])

  return redirect_to "http://www.google.com" if site_list.empty?

  site = site_list.first
  @html = site.html
  render "show_html.html.erb"
end

Upvotes: 2

alex
alex

Reputation: 3742

You don't need render (and site.html which is nil.html in else condition) after redirect. You need one of it.

def show_html
  site_list = Site.where(:url => params[:url])
  if site_list.length > 0
    site = site_list.first
    @html = site.html
    render "show_html.html.erb"
  else
    redirect_to "http://www.google.com"
  end
end

Upvotes: 2

rabid_zombie
rabid_zombie

Reputation: 992

It seems like instructions after redirects will be executed. Here is an article referencing this problem.

One way to solve this problem is to return the redirect like so:

def show_html
  site_list = Site.where(:url => params[:url])
  if site_list.length > 0
    site = site_list.first

  else
    return redirect_to "http://www.google.com"
  end

  @html = site.html
  render "show_html.html.erb"

end

Upvotes: 1

Related Questions