删除资源名称并使用mongoid_slug gem获取404响应

时间:2013-04-24 18:01:24

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 routes mongoid

namespace :blog do
 resources :posts, :only => [:index, :show], :path => "/"
end

如果我写:

http://localhost:3000/blog/post1

它工作正常。但是,如果我写:

http://localhost:3000/blog/invalid_id_fkdkflskdfl

我在日志中得到200回复​​:

Processing by Blog::PostsController#show as HTML
  Parameters: {"id"=>"invalid_id_fkdkflskdfl"}
  MOPED: 127.0.0.1:27017 QUERY        database.............................
Completed 200 OK in 60ms

在我的模特中:

class Post
 include Mongoid::Document
 include Mongoid::Slug
 #slug
 slug :title
 #fields
 field :title
end

这是我的动作节目:

def show
 @post = Post.find(params[:id])
end

我正在使用mongoid_slug gem

如果此ID invalid_id_fkdkflskdfl不存在,为什么我没有收到404回复?

如何获得404回复?

1 个答案:

答案 0 :(得分:0)

如果要呈现404响应,可能会捕获此异常并引发路由错误。您可以在控制器中执行此操作,例如:

application_controller.rb文件中:

class ApplicationController < ActionController::Base

  rescue_from Mongoid::Errors::DocumentNotFound, :with => :render_not_found

  def render_not_found
    render file: "#{Rails.root}/public/404", formats: [:html], status: 404, layout: false
  end

  ...

end

我的posts_controller.rb档案:

def show
 @post = Post.find(params[:id]) || render_not_found
end

感谢您在此link

中的digitalplaywright

问候!