当我进入文章/编辑时,我收到了一个错误。
当我收到此错误时:
我的代码:
articles_controller:
class ArticlesController < ApplicationController
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
flash[:notice] = "Article was submitted succsefully"
redirect_to (@article)
else
render :new
end
end
def show
@article = Article.find(params[:id])
end
private
def article_params
params.require(:article).permit(:title, :description)
end
end
我的edit.html.erb:
<h1>Edit the existing article</h1>
<% if @article.errors.any? %>
<h2>The following errors are informing you that if you don't do these then
your articles will not be edited</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li> <%= msg %> </li>
<% end %>
</ul>
<% end %>
<%= form_for @article do |f| %>
<p>
<%= f.label :title %>
<%= f.text_field:title %>
</p>
<p>
<%= f.label :description %>
<%= f.text_area :description %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
我的new.html.erb:
<h1>Create an article</h1>
<% if @article.errors.any? %>
<h2>The following errors are informing you that if you don't do these then
your articles will not be created</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li> <%= msg %> </li>
<% end %>
</ul>
<% end %>
<%= form_for @article do |f| %>
<p>
<%= f.label :title %>
<%= f.text_field:title %>
</p>
<p>
<%= f.label :description %>
<%= f.text_area :description %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
my routes.rb:
resources :articles
root 'pages#home'
get 'about', to: 'pages#about'
如果有帮助,请向我询问更多文件
答案 0 :(得分:6)
那就是错误的原因。 “编辑”页面需要一个id参数。在你的控制器中:
def edit
@article = Article.find(params[:id])
end
需要params[:id]
因此您需要使用/articles/id/edit
(将id替换为您的实际ID)
答案 1 :(得分:2)
resources :articles
将创建一个edit_article_path
帮助程序,您应该用它来链接到编辑操作:
<%= link_to("Edit article", edit_article_path(@article)) %>
这将使用:id
细分创建正确的路径:
Prefix Verb URI Pattern Controller#Action
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy