Reputation: 1374
I am trying to get the validation working for my comment form assignment. For some reason all I get is my flash error being returned back to me. The way it is reacting (absolutely no output), I suspect I have not specified things properly.
Comments will only need to be created for now, so generate a comments_controller with the appropriate action;
Fill in the create action. It should create a new comment associated with a post and the current_user who created it;
flash[:error] = "Error saving the comment. Please try again."
_form.html.erb
<%= form_for [topic, post, comment] do |f| %>
<% if comment.errors.any? %>
<div class="alert alert-danger">
<h4>There are <%= pluralize(comment.errors.count, "error") %>.</h4>
<ul>
<% comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-inline">
<%= form_group_tag(comment.errors[:body]) do %>
<%= f.label :body %>
<%= f.text_field :body, class: 'form-control'%>
<% end %>
<div class="form-group">
<%= f.submit "Comment", class: 'btn btn-default' %>
</div>
</div>
<% end %>
in the form_group_tag I specified :body to match my label/text field.
here is my Comment model with :body and :user being specified
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
# minimum 5 characters and must be signed in
validates :body, length: { minimum: 5 }, presence: true
validates :user, presence: true
end
comments_controller.rb
class CommentsController < ApplicationController
def create
# find topic by id
@topic = Topic.find(params[:topic_id])
# find post id through topic
@post = @topic.posts.find(params[:post_id])
# comments on post
@comments = @post.comments
@comment = current_user.comments.build(params.require(:comment).permit(:body, :post_id))
@comment.post = @post
if @comment.save
flash[:notice] = "Your comment was created."
redirect_to [@topic, @post]
else
flash[:error] = "Error saving the comment. Please try again."
redirect_to [@topic, @post]
end
end
end
If I press the submit button the flash error only appears, nothing related to the validation is returned back to me.
Upvotes: 0
Views: 1039
Reputation: 1302
In comments_controller.rb you redirect on error, which reloads the page and resets the record. You should render the form view.
Try replacing the line
redirect_to [@topic, @post]
with
render :new
if @comment.save
fails. (I assume you're following conventional naming.)
EDIT:
You'll might want to render the view that includes the "comments/_form" partial. I assumed it was "comments/new", but judging by your comments you might be looking for "posts/show". Render defaults to the current controller's views, but this can easily be overridden.
render "posts/show"
Upvotes: 2