什么会导致我的Ruby on Rails控制器中的操作被重复调用?

时间:2010-10-19 00:40:42

标签: ruby-on-rails

Helllo。我正在深入研究RoR,在安装Paperclip并设置我的代码以适应它之后,我的一个控制器中的新方法导致了StackOverflow;)。我正在运行Rails 3.0和Ruby 1.8.7。任何人都可以猜测或告诉我可能导致我的new动作被重复调用的原因是什么?

这是服务器输出......

Started GET "/projects/new" for 127.0.0.1 at Mon Oct 18 19:25:42 -0500 2010
  Processing by ProjectsController#new as HTML
Completed   in 1192ms

SystemStackError (stack level too deep):
  app/controllers/projects_controller.rb:27:in `new'
  app/controllers/projects_controller.rb:27:in `new'
  app/controllers/projects_controller.rb:30:in `new'
  app/controllers/projects_controller.rb:29:in `new'
  .
  . 
  .
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.erb (3.6ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (4.3ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (63.9ms)

这是我的控制器代码......

def new
    @project = Project.new

    respond_to do |format|
      format.html new.html.erb
      format.xml  { render :xml => @project }
    end
  end

以下是new模板的视图代码...

<%= form_for(:project, @project, :html => {:id => "project_form", :multipart => true}) do |f| %>
  <% if @project.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@project.errors.count, "error") %> prohibited this project from being saved:</h2>

      <ul>
      <% @project.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :tech_used %><br />
    <%= f.text_field :tech_used %>
  </div>
  <div class="field">
    <%= f.label :owner %><br />
    <%= f.text_field :owner %>
  </div>
  <div class="field">
    <%= f.label :created %><br />
    <%= f.date_select :created %>
  </div>
 <div class="field">
  <%= f.file_field :thumbnail %>
 </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

使用以下内容:

def new
  @project = Project.new

  respond_to do |format|
    format.html
    format.xml  { render :xml => @project }
  end
end

使用format.html new.html.erb,您再次调用new方法;如果它返回,你将调用.html方法,这将导致方法未找到错误。相反,它会递归调用new,直到内存不足为止。