おはようございます。form_withでエラーが表示されない
私はチュートリアルhttp://edgeguides.rubyonrails.org/getting_started.htmlを以下だし、私は次を見つける:
私はArticlesControllerと呼ばれるコントローラを持っています。 createメソッドは "if @ article.save"ステートメントを使用して@articleオブジェクトを保存します。何か問題が生じた場合は 'new'をレンダリングします。同様に、更新メソッドは、その記事のレコードを更新するために "if @ article.update(article_params)"を使用し、何かが間違っていれば 'edit'をレンダリングします。
新しいビューと編集ビュー<%if @ article.errors.any? %>は、エラーがあったかどうかを判断し、対応するメッセージを表示するために使用されますが、問題は新しいビューでうまく動作しますが、編集ビュー@ 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
falseまたはnilをチェックします。これは、ブロックでの使用のための設計です。 errors配列が空の場合、[] .any? =>真。プレゼントを使ってみませんか?と空白?最初に方法。 –
次の方法を試して、エラーがまだ存在するかどうか確認できますか? <%= form_for @article、url:articles_path do | f | %> 「新規」と「編集」ページの両方で –
ああ、ありがとう!そうすれば、既存の記事を更新するために新しい記事を作成できます。 :( –