Reputation: 824
I have a question model:
class Question < ActiveRecord::Base
has_many :answers, :dependent => :destroy
That has many answers:
class Answer < ActiveRecord::Base
belongs_to :question, :counter_cache => true
validates :body,
:presence => true,
:length => {:minimum => 3, :maximum => 4096}
I have a form under a question page, so I can submit answers.
The problem is that after I create a new answer I'm redirected back to the question so, I cannot see any validation errors.
Does anyone knows how to see validation errors from answers on a question page?
This is views/questions/show.html.erb
<%= render :partial => @answers %>
<%= form_for [@question, Answer.new] do |f| %>
<div class="formline">
<div class="formlabelcenter"><%= f.label :body, "New Answer" %></div>
<div class="formfield"> <%= f.text_area :body, :class => "mceEditor" %></div>
</div>
<div class="formline">
<div class="submit">
<%= f.submit "Add Answer" %></div>
</div>
<% end %>
When I try to render the question it gets me to:
http://0.0.0.0:3000/questions/question-name/answers
and not to
http://0.0.0.0:3000/questions/question-name
Upvotes: 0
Views: 531
Reputation: 9815
You have nothing displaying the errors in your view code that displays the question form, try this (note the change of Answer.new to @answer, so this will display the same model that fails validation in the controller)
<%= form_for [@question, @answer || Answer.new] do |f| %>
<% if @answer && @answer.errors.any? %>
<div class='errors'>
<h2>
<%= pluralize(@answer.errors.count, "error") %>
prohibited this user from being saved:
</h2>
<ul>
<% @answer.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% # your view code here %>
<% end %>
Upvotes: 1
Reputation: 1843
When detecting the error in your controller, store its message in flash[:error]
. Then, in the view, check for the existance of :error
in the flash
hash. If it exists, display it as an error message.
Upvotes: 0