Ruby on Rails - f.error_messages not showing

I've read a lot of posts about this issue, but I never got it to work.

My model looks like this:

class Announcement < ActiveRecord::Base
    validates_presence_of :title, :description
end

      

My controller creation method (just the relevant part of it) looks like this:

def create
    respond_to do |format|
      if @announcement.save
        flash[:notice] = 'Announcement was successfully created.'
        format.html { redirect_to(@announcement) }
        format.xml  { render :xml => @announcement, :status => :created, :location => @announcement }
      else
        @announcement = Announcement.new
        @provinces = Province.all
        @types = AnnouncementType.all
        @categories = Tag.find_by_sql 'select * from tags  where parent_id=0 order by name asc'
        @subcategories= ''
        format.html { render :action => "new" } #new_announcement_path
        format.xml  { render :xml => @announcement.errors, :status => :unprocessable_entity }
      end
    end
  end

      

My form looks like this:

<% form_for(@announcement) do |f| %>
    <%= error_messages_for 'announcement' %> <!--I've also treid f.error_messages-->
...

      

What am I doing wrong?

+2


a source to share


1 answer


You kill your error messages by creating a new declaration in your else statement.

@announcement = Announcement.new # should be removed

      



When called, @announcement.save

it will store errors in @announcement.errors

. Calling @announcement = Announcement.new

after that will return you to a clean slate. Therefore, there will be no errors.

+5


a source







All Articles