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?
It seems like instructions after redirects will be executed. Here is an article referencing this problem.
One way to solve this problem is to
returnthe 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