views:

114

answers:

1

Hi there,

I have an object Tasks with a model like this

  has_many :notes, :validate => true

And Notes with a model like this:

  belongs_to :task
  validates_presence_of :body, :message => "cannot be empty, bonehead!"

I have a /tasks/new view to create a new task (form _for), and a note for it (fields _for). I want the validation failure messages for the Task and Note to be spat out at the top of the form.

The controller looks like:

def create
    @task = Task.new(params[:task])
    @note = Note.new(params[:note])
    @task.notes << @note
    if @task.save
       redirect_to tasks_path
    else
        render :action => 'new'
    end

The problem is, when no Note body is entered a validation error message is returned in @note, "Body cannot be blank, bonehead"; and another one in @task, "Note is invalid".

I'm spitting both out in the view like this:

 <%= error_messages_for 'task', 'note', 'users_list', :header_message => nil, :message => nil %>

I want to keep the Note model validation message, and not have one as part of the Task object, "Not is invalid".

Thanks a lot!

+2  A: 

I don't have a console in front of me, but I think if you change your if statement to if @note.valid? and @task.save it would check the note first and only give you the first message.

Edit: This is just kind of an FYI, but you might want to use build instead of two new statements:

def create
  @task = Task.new(params[:task])
  @note = @task.notes.build(params[:note])
  if @task.save
    ...
Matt Grande
Total win!Thanks for the help sir.
doctororange