0

我正在尝试创建一个从 1 个控制器提交到另一个控制器的表单。当我这样做时,我得到“nil:NilClass 的未定义方法'allow_forgery_protection'”。但是,如果我 POST 回同一个控制器,它会成功提交。

要知道的事情

  • 我的应用程序控制器已protect_from_forgery设置。我不是:before_filter为了减少可能出现的问题而搞砸或做任何事情。

  • 两种控制器都没有型号。两者都是用rails g controller <name>

  • Rails 3.2 如果它有所作为

应用程序/控制器/first_controller.rb

def myaction
end

app/views/first/myaction.html.erb

<%= form_tag(url_for(:controller => 'second', :action => controller.action_name), :method => :post) do %>
  <fieldset>
    <%= label_tag(:file_dir, "File location") %>
    <%= text_field_tag :file_dir, "/var/log" %>
  </fieldset>
  <%= submit_tag "Submit" %>
<% end %>

应用程序/控制器/second_controller.rb

def myaction
end

app/views/second/myaction.html.erb

<h1>Second#myaction</h1>
<p>Find me in app/views/second/myaction.html.erb</p>

路线.rb

 match 'first/:action' => 'first#:action'
 match 'second/:action' => 'second#:action'

It's probably my lack of understanding about the CSRF, but I don't see how simply changing :controller => 'second'to :controller => 'first' will determine whether the nearly identical controllers will work.

Part of the log

# Rendered the form
Started GET "/first/myaction" for 127.0.0.1 at 2012-08-04 14:20:00 -0500
Processing by FirstController#myaction as HTML
Rendered first/myaction.html.erb within layouts/application (3.7ms)
Completed 200 OK in 142ms (Views: 141.9ms | ActiveRecord: 0.0ms)


# Submitted the form here
Started POST "/second/myaction" for 127.0.0.1 at 2012-08-04 14:22:00 -0500
Processing by SecondController#myaction as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xyQetj0Wdks+iuOXNjrxs96TbEJOw4ktURTrraEARoU=",<everything else looks fine>}
Completed 500 Internal Server Error in 0ms
NoMethodError (undefined method `allow_forgery_protection' for nil:NilClass):
4

1 回答 1

0

I created a third controller to test with (via the same exact steps), and the form performed a POST properly.

During this same time, the second threw this forgery error consistently.

I deleted the second controller with rails destroy controller second, and recreated it with rails g controller second, keeping the same routes in routes.rb, and everything worked properly.

于 2012-08-05T15:05:50.263 回答