开发者

Rails routing \ controller issue

开发者 https://www.devze.com 2023-03-10 17:13 出处:网络
routes.rb match \'/:permalink\' => \'Pub#show_page\' in pub_controller: def show_page @page = Page.find_by_permalink(params[:permalink])

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.c开发者_开发百科ontent %></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..


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消