这种脚手架有什么问题?

时间:2011-04-03 18:33:01

标签: ruby-on-rails rest

嘿伙计们,   我一般都没有使用脚手架,虽然我已经在使用Rails很长一段时间了。我大多数时候会手动做事。

现在,我正在尝试创建一个类似于表单的实现。我有一个form_for:

<% 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 %>

路线是:

  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  

现在,此表单由新操作生成:

def new
    @alliance = Alliance.new
end

提交内容如下:

def create
    @alliance = Alliance.new(params[:alliance])

    if @alliance.save
        flash[:error] = I18n.translate 'error.alliance_created'
        redirect_to alliance_path and return
    else
        redirect_to new_alliance_path and return
    end
end 

现在,如果出现错误,我在重定向到new_alliance_path时不会将其恢复。乍一看,这看起来很正常,因为new会重新创建@alliance实例变量。但是,在一些脚手架代码中,似乎它以类似的方式完成。

你能看到我做错了吗?

1 个答案:

答案 0 :(得分:1)

您的创建操作应该更像是这样:

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

调用重定向时,再次启动完整的请求生命周期。相反,您只想使用当前的@alliance对象重新渲染新视图。

我还注意到你使用4个空格来缩进。 Ruby标准是2。