具有条件的轨道中的动态路径

时间:2013-02-18 03:57:02

标签: ruby-on-rails-3 routing routes

我有一组带有公共属性的页面。我希望routes文件处理动态路由,但仅限于公共页面。

我目前有以下内容,但没有限制,所有页面都可见。我想要的是只有在页面公开的情况下才转到页面,否则加注404。

Page.public.each do |page|
  get "/:slug", controller: 'pages', action: 'show' if page.public?
end

2 个答案:

答案 0 :(得分:2)

我会将此行为放在控制器而不是routes.rb中,因为页面可能会在运行时从私有更改为公用,而生产中的路由只在开始时初始化一次。

class PagesController

  before_filter :is_public, only => [:show]

  protected

    # Check if the page is public, otherwise raise a routing error.
    def is_public
      raise ActionController::RoutingError.new unless Page.find(params[:slug]).public?
    end
end

答案 1 :(得分:0)

工作代码是(缺少'未找到')

class PagesController

  before_filter :is_public, only => [:show]

  protected

  # Check if the page is public, otherwise raise a routing error.
  def is_public
    raise ActionController::RoutingError.new('Not Found') unless Page.find(params[:slug]).public?
  end
end