opticon
opticon

Reputation: 3614

Rails Validation - Redirect not working

I feel somewhat stupid about this one, but:

if @prof.update_attributes(params[:profile])
      respond_to do |format|
        format.html {redirect_to(@prof, :notice => "Profile successfully created.") }
      end
    end

...is in the update method of my controller. I have some attributes being validated in the model.

If validation fails, I just want them back on the same form to be scolded by various red text. (ie. everything in the errors array).

I'm getting a 'template missing' error when validation fails - the template for 'update'. I feel like I'm overlooking something extremely simple. Help!

Upvotes: 1

Views: 65

Answers (2)

Paul Richter
Paul Richter

Reputation: 11081

The cause of the error is due to the fact that Rails, unless told otherwise, will attempt to render a template with the same name as the action, in this case update, which obviously doesn't exist.

What you want to do is tell rails to render the edit action again in the event of an error. Typically, you would do this with the respond_to block, allowing the block to respond differently depending on whether validation passed or failed.

At present, you have your if statement wrapping the block, and no statements telling rails to render differently in the event of an error. To fix this, I would do the following:

respond_to do |format|
    if @prof.update_attributes(params[:profile])
        # all is well, redirect as you already wrote
    else
        format.html { render action: 'edit' }
    end
end

Upvotes: 1

zwippie
zwippie

Reputation: 15525

Try this:

respond_to do |format|
  if @prof.update_attributes(params[:profile])
    format.html { redirect_to(@prof, :notice => "Profile successfully created.") }
  else
    format.html { render action: 'edit' }
  end
end

Upvotes: 2

Related Questions