Reputation: 1042
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?
model Post:
#/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
View for comment form:
<%= 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 %>
<%= render 'comments/form' %>
How to pass @comment from the controller CommentController to view /post/show.html.erb ?
Thanks in advance.
Upvotes: 9
Views: 13407
Reputation: 1812
you shouldn't redirect to post_path(@post)
if the comment is not valid.
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(params[:comment])
if @comment.save
redirect_to post_path(@post), notice: 'Comment was successfully created.'
else
render action: "posts/show", error: 'The comment you typed was invalid.'
end
end
end
and change the first form line in /views/comments/_form.html.erb
from:
<%= form_for([@post, @post.comments.build]) do |f| %>
to:
<%= form_for([@post, (@comment || @post.comments.build)]) do |f| %>
then you should see error messages when it fails to save.
Upvotes: 1
Reputation: 4588
And/Or take a look at Ryan Bates Screencasts about nested models and resources:
They're Rails 2 but to get an idea how it works it's ok.
Maybe also interesting for you:
Upvotes: 2
Reputation: 9018
Put render "posts/show"
instead of redirect_to post_path(@post)
in your CommentsController
.
Upvotes: 5