views:

162

answers:

1

Hi, I've read many posts about this issue but I never got this to work.

My model looks like this:

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

My controller's create method(only its relevant part) 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?

+5  A: 

You are killing your error messages by creating a new announcement in your else statement.

@announcement = Announcement.new # should be removed

When you call @announcement.save it will store the errors in @announcement.errors. By calling @announcement = Announcement.new after this you are going back to a clean slate. So no errors will ever be displayed.

Tony Fontenot
You're right. That was the problem. Do you know why I put those lines in the else statemente before rendering? Because I have combo boxes that need to be initialized with those variables(I create them in the "new" method) and if I didn't put them in the else clause, it will throw an exception. Could you tell me how can I reuse those lines to avoid repeating them everywhere? Thanks!
Brian Roisentul
Just create a private function in the controller that sets the variables and call the function when needed.
Tony Fontenot
Thank you! Now it works.
Brian Roisentul