What is wrong in this Scaffolding like way?
Hey guys, i generally haven't used scaffolds, though i've been messing with Rails for quite some time. I would most of the times do things manually.
Now, i'm trying to create a restful like form implementation. I have a form_for like :
<% form_for @alliance, :url => create_alliance_path do |f| %>
<% if @alliance.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(@alliance.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @alliance.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.label :name %>
<%= f.text_field :name %><br>
<%= f.label :description %>
<%= f.text_area :description %><br>
<%= f.label "Image URL" %>
<%= f.text_field :image_url %><br>
<%= f.submit "#{t 'alliance.create_button' }" %>
<% end %>
The routes are :
scope :path => '/alliances', :controller => :alliances do
get 'show/(:id)' => :show, :as => 'alliance'
get 'new' => :new, :as => 'new_alliance'
post 'create' => :create, :as => 'create_alliance'
end
Now, this form is generated by the new action :
def new
@alliance = Alliance.new
end
And the submission is like :
def create
@alliance = Alliance.new(params[:alliance])
if @alliance.save
flash[:error] = I18n.translate 'e开发者_开发百科rror.alliance_created'
redirect_to alliance_path and return
else
redirect_to new_alliance_path and return
end
end
Now, if there is an error, i do not get it back when redirecting to new_alliance_path. At first sight, this seems normal, as new recreates the @alliance instance variable. However, in some scaffolding code, it seems like it's done in a similar manner.
Can you see what i'm doing incorrectly ?
Your create action should look more like this:
def create
@alliance = Alliance.new(params[:alliance])
if @alliance.save
flash[:error] = I18n.translate 'error.alliance_created'
redirect_to alliance_path
else
render :action => :new
end
end
When calling redirect you start the complete request life-cycle again. Instead you just want to re-render the new view with the current @alliance object.
I also noticed you are using 4 spaces to indent. The Ruby standard is 2.
精彩评论