我目前正在学习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,并希望在这方面做得更好。会感谢你的帮助。
发布于 2018-03-28 17:47:02
按以下方式使用自定义url修改form_for
<%= form_for @article, url: @article.new_record? ? article_create_new_article_path : update_article(@post)do |f| %>但我建议你改用足智多谋的路由。
发布于 2018-03-28 17:43:25
首先,您确实应该为您的文章模型使用资源路由:
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)
endhttps://stackoverflow.com/questions/49540599
复制相似问题