dsp_099
dsp_099

Reputation: 6121

Rails routing \ controller issue

routes.rb

match '/:permalink' => 'Pub#show_page'

in pub_controller:

 def show_page

    @page = Page.find_by_permalink(params[:permalink])

     if @page.nil?
        render :status => 404
     end

 end

in show_page.html.erb:

<h1><%= @page.title %></h1>
<br>
<p><%= @page.content %></p>

Then I go to localhost:3000/non-existing-permalink

What is going on here? I always get the "undefined method `title' for nil:NilClass", meaning for some reason, the def show_page lets the browser through to the view. I've tried every possible variation of if and unless statements to try and fix it but it just always disregards the if statement.

If the permalink is correct, such as ..3000/existing-permalink/ it renders the page just fine.

Why is it ignoring the if statement? I'm baffled.

Thanks much..

Upvotes: 0

Views: 98

Answers (1)

cailinanne
cailinanne

Reputation: 8372

render :status => 404

just renders the usual page with a status code of 404. E.g. it's rendering show_page.html.erb with an Apache code of 404 (which, of course, is invisible to the user).

You want to redirect to a 404 page. See How to redirect to a 404 in Rails?

Upvotes: 1

Related Questions