I’m using Rails 2.3.8
I’m having an issue with the actions that get rendered after an error in a form.
So I have a posts controller and the regular related actions, index, new, create, edit, update, and show.
Here are the actions with forms in PostsController:
def new
@post = Post.new
# other setup
end
def create
if request.post?
@post= Post.new(params[:post])
# other setup for save
if @post.save
flash[:notice] = 'Post was successfully created.'
redirect_to campaign_path(@post, :redirect => "create")
else
render :action => 'new'
end
end
end
def edit
@post = Post.find(params[:id])
# other setup
end
def update
# setup for save
if @campaign.update_attributes(params[:post])
flash[:notice] = 'Your post was successfully updated.'
redirect_to :action=> "index"
else
render :action => "edit"
end
end
And here are the forms in the views
new.html.erb:
<% form_for(@post, :html => {:multipart => true}) do |f| %>
<%= f.error_messages %>
# Form fields and stuff
<%= f.submit "Create New Post" %>
<% end %>
edit.html.erb:
<% form_for(@post, :html => {:multipart => true}) do |f| %>
<%= f.error_messages %>
# Form fields and stuff
<%= f.submit "Update This Post" %>
<% end %>
My problem is: If I’m on the new page and I make some error (e.g. leave a field empty), the views that render submit to the wrong place. So if I start out on new and submit unsuccessfully a bunch of times, it takes me successively through new, then create, then edit, then update actions. So the behavior is:
Start out creating a post:
Action: new
URI: /posts/new
View rendered: new
Successful submit goes to: show
Unsuccessful submit goes to: create
After first unsuccessful submit:
Action: create
URI: /posts bad?
View rendered: new
Successful submit goes to: index (this means the form is submitting to the update action, bad)
Unsuccessful submit goes to: edit bad
After second unsuccessful submit:
Action: edit bad, I shouldn’t be able to get here from new!
URI: /posts/[id]
View rendered: edit bad, I shouldn’t be able to get here from new!
Successful submit goes to: index through update
Unsuccessful submit goes to: update
After third and subsequent unsuccessful submits:
Action: update bad, I shouldn’t be able to get here from new!
URI: /posts/[id]
View rendered: edit bad, I shouldn’t be able to get here from new!
Successful submit goes to: index
Unsuccessful submit goes to: update
I’d appreciate if anyone can point me to what I’m doing wrong. If you need any additional information just ask.
Thanks so much!
The problem is probably the code that you are using to create your post (# setup for save). You are probably setting @post.id which is causing your new form to submit to update instead of create. The form_for helper checks if a record is new or not, if it is new then it submits to create, if it already exists it submits to update.
Note: You also don’t need to check request.post? on your create action. The create action should always be a post request.