I’m trying to create a form that submits from 1 controller to another. When I do so, I get “undefined method ‘allow_forgery_protection’ for nil:NilClass”. However, if I POST back to the same controller, it successfully submits.
Things to know
-
My application controller has
protect_from_forgeryset. I’m not
messing with:before_filteror anything in order to reduce
possible problems. -
There is no model for either controller. Both were generated with
rails g controller <name> - Rails 3.2 if it makes a difference
app/controllers/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 %>
app/controllers/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>
routes.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):
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 withrails g controller second, keeping the same routes in routes.rb, and everything worked properly.