没有路由匹配 [PUT],但我在 routes.rb 中包含"resources"



我正在编写一个博客,它有两种类型的文章:"草稿"one_answers"已发表"。我正在使用aasm宝石使文章从草稿过渡到发布或viceverza。还有三种用户:"普通读者"、"编辑者"one_answers"管理员"。

当用户写文章时,管理员可以评估是否发布它们。为了实现这一点,管理员有一个视图,他们可以看到草稿和发表的文章。

问题是,当我试图发布文章时,我得到了No route matches [PUT] "/articles"错误,无论我在routes.rb中添加了resources :articles

我写的代码如下:

routes.rb

resources :categories
resources :articles do
   resources :comments, only: [:create, :update, :destroy, :show]
end 
devise_for :users
root 'welcome#index'
get '/dashboard', to: 'welcome#dashboard'
put '/articles/:id/publish', to: 'articles#publish'

articles_controller.rb

...
def publish
     @article.publish! # Article transition from draft to published.
     redirect_to @article
end
...

dashboard.html.erb

...
<% @articles.each do |art| %>
<h1><%= link_to art.title, art, method: :get %> | id = <%= art.id %> | user_id = <%= art.user_id %></h1>
<div>
    <%= art.body %> - <%= link_to "Eliminar", art, method: :delete %>
    <% if art.may_publish? %>
        - <%= link_to "Publicar", '/articles/#{article.id}/publish' , method: :put %>
    <% end %>
</div>
<% end %>
...

我不明白为什么我得到这个错误,如果我包括文章资源。如果你需要我添加更多的代码,不要犹豫,请告诉我。

你应该删除你的自定义路由,并把它放到resources:articles中,像这样:routes.rb

resources :articles do
  put 'publish', on: :member
  resources :comments, only: [:create, :update, :destroy, :show]
end

,你应该在你的视图中使用它:

<%= button_to "Publicar", publish_article_path(article), method: :put %>

它将生成一个表单

代码似乎是正确的,所以尝试重置服务器,顺便重新启动浏览器。它通常可以解决像这样的奇怪问题:)告诉我它是否有效。

最新更新