【问题标题】:remove resource name and get 404 response with mongoid_slug gem删除资源名称并使用 mongoid_slug gem 获得 404 响应
【发布时间】:2013-04-24 18:01:24
【问题描述】:
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 响应?

【问题讨论】:

  • 也许在你的控制器中你查询Blog.find(params[:id]),并且不要以你想要的方式操作渲染。
  • 我已经用更多信息更新了我的问题。谢谢!

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


【解决方案1】:

如果要呈现 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

感谢 digitalplaywright 在此link

问候!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多