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.
Put render "posts/show"
instead of redirect_to post_path(@post)
in your CommentsController
.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With