Rails 使用了错误的自定义命名路由

Rails using wrong custom named route

我正在构建一个博客 post 版本控制系统,用户可以在其中执行以下操作:

  1. 将草稿 Post 更改为已发布 Post
  2. 存档已发布
  3. 重新发布并存档 Post

Post的状态设置在Post的一列,状态可以是"Draft"、"Active"、"Archive"

现在,每当我点击 "publish" 或 "republish" 时,它会将页面标记为 "archived."

PostsController.rb

def mark_published
  @post = Post.find(params[:id])
  @post.update(status: 'active')
  @post.save
  redirect_to confirmation_admin_post_path(@post.id), notice: 'post has been Published.'
end

 def mark_archived
    @post = Post.find(params[:id])
    @post.status = 'archived'
    @post.save
    redirect_to confirmation_admin_post_path(id: @post.id), notice: 'post has been archived.'
 end

show.html.slim

 .col-sm-6.col-md-2.col-lg-2
   = link_to 'PUBLISH ', mark_published_admin_post_path(@post), class: 'btn btn-success btn-block mb15 btn-lg '
 .col-sm-6.col-md-2.col-lg-2
   = link_to 'ARCHIVE ', mark_archived_admin_post_path(@post), class: 'btn btn-success btn-block mb15 btn-lg 

'

routes.rb

namespace :admin do
  resources :posts do
      member do
       get 'posts',  to: 'posts#mark_archived', as: :mark_archived
       get 'posts',  to: 'posts#mark_published', as: :mark_published
       get 'posts',  to: 'posts#confirmation', as: :confirmation
    end 
  end
end

更新:

mark_archived_admin_post GET    /admin/posts/:id/posts(.:format)                admin/posts#mark_archived
 mark_published_admin_post GET    /admin/posts/:id/posts(.:format)                admin/posts#mark_published
 mark_archived_admin_post GET    /admin/posts/:id/posts(.:format)                admin/posts#mark_archived
 confirmation_admin_post GET    /admin/posts/:id/posts/confirmation(.:format)     admin/posts#confirmation

rake routes 的输出所示,您的 routes.rb 文件似乎不正确。通过这种方式,您将创建 3 个名称不同的路由,并执行不同的控制器操作但路径相同,即 GET 到 /admin/posts/:id/posts。尝试将您的文件更改为如下内容:

namespace :admin do
  resources :posts do
    member do
      post 'mark_archived',  to: 'posts#mark_archived', as: :mark_archived
      post 'mark_published',  to: 'posts#mark_published', as: :mark_published
      post 'confirmation',  to: 'posts#confirmation', as: :confirmation
    end 
  end
end

post vs get 没那么重要。重要的是它们并不都是 get 'posts'.