我目前正在学习铁轨并面临一个完全奇怪的问题。我正在尝试通过遵循我正在做的教程来更新现有文章,但是它没有更新。我分别从终端和浏览器中收到以下错误:
- 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 %>
我肯定不是我在做错什么,因为所选文章没有更新。
到目前为止,我一直很喜欢铁轨,并希望能变得更好。将感谢任何帮助。
用自定义URL
修改form_for
<%= form_for @article, url: @article.new_record? ? article_create_new_article_path : update_article(@post)do |f| %>
,但我建议您改用足智多谋的路由。
首先,您确实应该为您的文章模型使用资源路由:
Rails.application.routes.draw do
root 'pages#index'
resources :articles
end
这就是控制器的外观。关于允许参数在此处阅读。
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