rails:ActionController :: RoutingError(没有路由匹配[PATCH]" / article / viewing-article-2"):

时间:2018-03-28 17:20:12

标签: ruby-on-rails ruby

我目前正在学习rails并面临一个非常奇怪的问题。 我正在尝试通过遵循我正在做的教程更新现有文章,但它没有得到更新。我分别从终端和浏览器收到以下错误:

- Terminal: 
* Started PATCH "/article/viewing-article-2" for 127.0.0.1 at 2018-03-28 18:54:46 +0200
* No route matches [PATCH] "/article/viewing-article-2"
- Browser: ActionController::RoutingError (No route matches [PATCH] "/article/viewing-article-2"):

我的路线如

**routes.erb**

Rails.application.routes.draw do

  root to: 'pages#index'

  post 'article/create-new-article', to: 'pages#create'

  get 'article/viewing-article-:id', to: 'pages#show', as: 'article'

  get 'article/:id/edit', to: 'pages#edit', as: 'article_edit'

  patch 'article/:id/update', to: 'pages#update', as: 'update_article'

  get 'article/new-article', to: 'pages#new'

  get 'article/destroy', to: 'pages#destroy'

end

和我的控制员:

controller.erb

def index
    @articles = @@all_articles.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    article_params = params.require(:article).permit(:title, :author, :publisher, :content)
    @article.update(article_params)
    redirect_to root_path
  end

和我的HTML:

edit.html.erb

<% content_for :title do %>Editing <%= @article.title %><% end %>

<% content_for :bodycontent do %>

 <h3>Editing <%= @article.title %></h3> 

  <%= form_for @article do |f| %>
     <%= f.text_field :title,  class: 'form-control'%>
     <%= f.text_field :author,  class: 'form-control'%>
     <%= f.text_field :publisher,  class: 'form-control'%>
     <%= f.text_area :content,  class: 'form-control'%> 
     <%= f.submit class: 'form-control btn btn-primary' %>
  <% end %>

<% end %>

我不确定我做错了什么,因为所选文章没有更新。

到目前为止,我一直喜欢rails,并希望能够更好地使用它。将不胜感激任何帮助。

2 个答案:

答案 0 :(得分:1)

首先,您确实应该使用resource routing作为文章模型:

Rails.application.routes.draw do
  root 'pages#index'
  resources :articles
end

这就是控制器应该是什么样子。关于许可证参数here

def index
  @articles = Article.all
end

def show
  @article = Article.find(params[:id])
end

def edit
  @article = Article.find(params[:id])
end

def update
  return unless request.patch?
  @article = Article.find(params[:id])

  if @article.update(article_params)
    redirect_to root_path
  else
    render :edit
  end
end

private

def article_params
  params.require(:article).permit(:title, :author, :publisher, :content)
end

答案 1 :(得分:1)

使用自定义网址

修改form_for,如下所示
<%= form_for @article, url: @article.new_record? ? article_create_new_article_path : update_article(@post)do |f| %>

但我建议您改用Resourceful Routing。