Keeping form content after validation fails

I have a form that has the following fields:

Name

Post Title

Post Body

The model does a validates_presence_of for each field, so if a user
fails to enter one or all fields, it will fail validation and redirect
back to the form.

This works perfectly, but unfortunately, if a user spends 30 minutes
writing a new post, but forgets to fill out a field, they get
redirected back to the form but loose all the content that they had
typed in!

Any advice on how to go about passing the form data BACK to the form
after it fails validation?

So no one has any idea how I might go about this?

I’m completely out of ideas…

What you want to do is use a “render” instead of a “redirect_to” when
the validation fails:

def create
@post = Post.create(params[:post])
if @post.valid?
# do whatever
else
render :action => :new
end
end

You can read more about this in the Rails API (http://
api.rubyonrails.org)


Thiago J.
http://www.railsfreaks.com

You need to use “render” instead of “redirect_to” in your method:

def create
@post = Post.create(params[:post])
if @post.valid?
# do whatever
else
render :action => :new
end
end

You can read more about this in the Rails API (http://
api.rubyonrails.org)


Thiago J.
http://www.railsfreaks.com

Sorry for the double post, was having a connection problem.

histrionics wrote:

I have a form that has the following fields:

Name

Post Title

Post Body

The model does a validates_presence_of for each field, so if a user
fails to enter one or all fields, it will fail validation and redirect
back to the form.

This works perfectly, but unfortunately, if a user spends 30 minutes
writing a new post, but forgets to fill out a field, they get
redirected back to the form but loose all the content that they had
typed in!

Any advice on how to go about passing the form data BACK to the form
after it fails validation?

In your view, use the params hash to supply the values to the form
fields:

text_field_tag :title, params[:title]
text_area_tag :body, params[:body]

This is for when you use a form_tag. I just did some experimenting, and
it appears to happen automatically when using form_for. I don’t know if
it actually is or if I’ve got something wonky going on.

Peace,
Phillip