早上好。
我正在按照教程进行操作http://edgeguides.rubyonrails.org/getting_started.html http://edgeguides.rubyonrails.org/getting_started.html我发现以下内容:
我有一个名为 ArticlesController 的控制器。 create方法使用“if @article.save”语句来保存@article对象,如果出现问题则渲染“new”。类似地,更新方法使用“if @article.update (article_params)”来更新该文章的记录,如果出现问题则呈现“编辑”。
在新视图和编辑视图中 用于判断是否有错误并显示相应的消息,但问题是在新视图中工作正常,但在编辑视图中 @article.errors.any 视图呢?即使有错误也返回 false。
有人可以告诉我出了什么问题吗?非常感谢。
然后我放置了 ArticlesController 类、视图 new.html.erb 和 edit.html.erb 以及文章模型。
class ArticlesController < ApplicationController
def new
@article = Article.new
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
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
------------------------------------------------------------------
<h1>New Article</h1>
<%= form_with scope: :article, url: articles_path, local: true do |form| %>
<% 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>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :text %><br>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
----------------------------------------------------------------------
<h1>Edit article</h1>
<%= form_with(model: @article) do |form| %>
<% 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>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :text %><br>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
---------------------------------------------------------------------
class Article < ApplicationRecord
validates :title, presence: true,
length: { minimum: 5 }
validates :text, presence: true
end
默认情况下,由 form_with 生成的所有表单都将通过 XHR (Ajax) 请求提交。如果您想禁用远程表单,那么您可以使用本地表单来执行此操作,就像在 new.html.erb 中的表单中所做的那样。
在 edit.html.erb 中更改此内容:
<%= form_with model: @article, local: true do |form| %>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)