渲染静态页面时的Rails路由冲突

Pat*_* A. 3 ruby ruby-on-rails ruby-on-rails-3

我有路由冲突。将所有博客文章从/posts/:id移到/:id(很棒)之后,我现在遇到一个问题,我的静态页面不包含ID,因此无法呈现。我不想通过我的posts控制器处理它们。

这是我的routes.rb文件中当前包含的内容:

  resources :posts, only: [:index, :create, :edit, :new, :destroy]
  get '/:id' => 'posts#show', :as => 'custom_url'
  match '/posts/:id' => redirect('/%{id}', status: 301)
Run Code Online (Sandbox Code Playgroud)

但是这些现在不起作用了...

  match '/privacy' => 'static#privacy'
  match '/terms' => 'static#terms'
Run Code Online (Sandbox Code Playgroud)

我有一个名为static_controller.rb的控制器,可以在需要时使用。我该如何跳过/:id比赛。

更新:

还遇到了我的def更新无法更新我的内容的问题。

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

    respond_to do |format|
      if @post.update_attributes(params[:post])
        format.html { redirect_to @post, :notice => 'Post was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render :action => "edit" }
        format.json { render :json => @post.errors, :status => :unprocessable_entity }
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

小智 7

Rails会按照从上到下的顺序匹配路线,因此,从上到下的优先级越高。请参见中的从外部进行Rails布线。如果您移动这些路线

  match '/privacy' => 'static#privacy'
  match '/terms' => 'static#terms'
Run Code Online (Sandbox Code Playgroud)

在这些路由上方,则静态路由将优先于博客帖子,并应正确呈现。

  resources :posts, only: [:index, :create, :edit, :new, :destroy]
  get '/:id' => 'posts#show', :as => 'custom_url'
  match '/posts/:id' => redirect('/%{id}', status: 301)
Run Code Online (Sandbox Code Playgroud)

请注意,这意味着如果您有任何博客文章ID与静态页面路由冲突,则静态页面将匹配并显示。

  • 如果ID是数字而不是静态页面,则`get'/:id'`上的`constraints:{id:/ \ d + /}`是另一种选择。 (4认同)