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

时间:2019-10-20 20:24:55

标签: ruby-on-rails ruby 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)

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

  match '/privacy' => 'static#privacy'
  match '/terms' => 'static#terms'

我有一个名为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

2 个答案:

答案 0 :(得分:7)

Rails从顶部到底部匹配路由,因此,顶部到顶部的优先级越高。参见Rails Routing from the Outside In。如果您移动这些路线

  match '/privacy' => 'static#privacy'
  match '/terms' => 'static#terms'

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

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

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

答案 1 :(得分:0)

为避免出现您描述的情况,请勿匹配并通过重定向绕过/posts/。这打破了层次结构和顺序的轨道模式,并可能使您的代码变得比所需的更混乱。 @Chris Selemers的回答是正确的,但正如他指出的那样,这种方法存在潜在的风险(如果非常有限)。

get '/posts/:id' => 'posts#show', :as => 'custom_url'

或者更好地做:

resources :posts