I do a simple blog on rails. I have a Post model and a Comment model. When you create a comment, if comment is not valid, i want to show the error. How do I do?
模式员额:
#/models/post.rb
class Post < ActiveRecord::Base
has_many :comments
validates :title, :content, :presence => true
end
model Comment:
#/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
validates :name, :comment, :presence => true
end
Comments Controller
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
end
意见表:
/views/comments/_form.html.erb
<%= form_for([@post, @post.comments.build]) do |f| %>
<% if @comment.errors.any? %>
error!
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
/views/posts/show.html.erb
<%= render comments/form %>
如何从控制员评论员那里通过@comment来看待/post/show.html.erb?
Thanks in advance.