如果编辑和更改值,代码工作正常,但如果我更新相同的值,则会创建新记录。
我只是关注ruby教程,并坚持这个问题。我对ruby和rails很新。
Controller:articles_controller.rb
class ArticlesController < ApplicationController
def create
#render plain: params[:article].inspect
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def new
@article = Article.new
end
def show
@article = Article.find(params[:id])
end
def index
@articles = Article.all
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
private
def article_params
params.require(:article).permit(:title_article, :text_article, :author_article)
end
end
表格:_form.html.erb
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title_article ,"Title" %><br>
<%= f.text_field :title_article %>
</p>
<p>
<%= f.label :text_article ,"Content" %><br>
<%= f.text_area :text_article %>
</p>
<p>
<%= f.label :author_article ,"Author" %><br>
<%= f.text_field :author_article %>
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
新文章页面:new.html.erb
<h1>Edit Page</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>
修改文章页面:edit.html.erb
<h1>New Page</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>
答案 0 :(得分:0)
正如@Cyril DD在评论中所说,_form.html.erb中的代码在第一行应该有<%= form_for(@article) do |f| %>
。 (我想它应该引发语法错误......)
_form.html.erb
<%= form_for(@article) do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
...
我复制了所有代码并添加了该行。然后,一切正常。即使在编辑中没有更改任何值,它也没有制作新文章。