1

私はRails Guides - Getting Startedチュートリアルに従っています。基本的な Post モデルと、Post に属する Comment モデルを作成します。

Comment モデルに簡単なバリデーションを追加しましたが、動作しますが、間違って入力した場合にフォーム エラーを表示する方法がわかりません。

ここに私のcomment.rbモデルがあります

class Comment < ActiveRecord::Base
  validates :body, presence: true
  belongs_to :post
end

これはコメントを追加するための元のフォームです。posts/show.html.erb にあります。

<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
  <div class="field">
    <%= f.label :commenter %><br />
    <%= f.text_field :commenter %>
  </div>

  <div class="field">
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

そして、comments_controller.rb の元の create アクション

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
end

いろいろ試してみましたが、どれも暗闇の中をいじっているように感じます。誰かが私を正しい方向に向けることができますか?

4

1 に答える 1

1

dynamic_form gemを見てください。これは以前はRail自体の一部でしたが、しばらく前に抽出されました。これを使用すると、次のようにエラーをインラインで表示できます。

<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
<%= f.error_message_on :commenter %>
于 2012-04-18T07:45:28.723 に答える