I have an Entry model and a Photo model and for each photo, users can submit an “entry” — just some text about the photo. On the show page for each photo, I render the full form for the entry. In my entry.rb file, I have the following to count the words of the entry:
validate :count_words
def count_words
body_size = body.to_s.scan(/[\w-]+/).size
unless body_size < 300
errors.add(:entry, "Your entry is too long")
end
end
When I test an entry that is more than 300 words, the save fails and my controller redirects back to the page they were one. Two problems. First error messages aren’t showing up when the controller redirects. I have this rendered w/ the form (it was generated by scaffold).
<% if @entry.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@entry.errors.count, "error") %> prohibited this entry from being saved:</h2>
<ul>
<% @entry.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
This is the controller action, where I suspect the problem lies:
def create
@entry = Entry.new(params[:entry])
respond_to do |format|
if @entry.save
format.html { redirect_to(@entry, :notice => 'Your entry was submitted.') }
else
format.html { redirect_to :back }
end
end
end
I’m not quite sure where the problem is. I plan to implement some javascript on the form to validate before the submission anyway, but I want this as a back up. Can someone tell me what I’m doing wrong?
Typically you’d want to have your
elsestatement do aformat.html { render :edit }instead ofredirect :back.When you redirect, the errors don’t persist (as they’re not saved to the database or session).