2009/10/15 Pål Bergström <[email protected]>:
> How should a create look like in order to get error_messages being
> displayed, going back to new and show the error message? I can't get it
> working so I must miss something.
If the create fails, the controller could/should (re)render the "new" view.
The "new" view should display there error messages.
The default behavior as exemplified by the scaffold looks something
like this in the controller:
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(@post) }
format.xml { render :xml => @post, :status => :created,
:location => @post }
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status =>
:unprocessable_entity }
end
end
end
If the save is successful, the user is redirected to the #show view.
If the save was unsuccessful, the #new view is rendered.
Notice the difference between a redirect, and a render (this took me a
little while to wrap my head around). A redirect tells the browser to
grab a completely new page (in this case the page associated with the
#show action), A render tells Rails what it should render for the
current page (in this case, the #new view).
If you look at the (standard, scaffold generated) #new view, you
should see something like:
<h1>New post</h1>
<% form_for(@post) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', posts_path %>
the f.error_messages displays the error messages associated with @post.
The key here is that @post is initialized to Post.new when the #new
action is called, but it contains the (unsaved) record with the bad
fields when the #new view is rendered from the #create action.
I hope this made more sense than it confused you.
--wpd
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---