路由错误:ApplicationController类中'with'未定义的本地变量或方法

3

我完全不了解Rails,也不知道为什么会出现这个错误:

undefined local variable or method `with' for ApplicationController:Class

路由:

root 'home#index'

控制器:

class HomeController < ApplicationController

  def new
  end

  def index
  end

end

应用程序追踪:

app/controllers/application_controller.rb:4:in `<class:ApplicationController>'
app/controllers/application_controller.rb:1:in `<top (required)>'
app/controllers/home_controller.rb:1:in `<top (required)>'

我已更新一些模型和rspec代码以测试模型验证,但是除此之外,我没有创建任何其他控制器/视图/路由等。
注意:ruby 2.0.0,rails 4.0.0
应用程序控制器:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with::exception
end

也许是某个Ruby宝石出了问题?
宝石清单文件:
source 'https://rubygems.org'
ruby '2.0.0'


# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby


gem 'rails', '4.0.0'

group :development do
  gem 'sqlite3', '1.3.7'
  gem 'rspec-rails', '2.14.0'
  gem 'guard-rspec', '3.0.2'
  gem 'guard-spork', '1.5.1'
  gem 'factory_girl', '4.2.0'
  gem 'factory_girl_rails', '4.2.1'
end
gem 'mysql', '2.9.1'
gem 'mysql2', '0.3.13'

gem 'sass-rails', '4.0.0'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.0'
gem 'jquery-rails', '2.2.1'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.2'


group :test do
  gem 'email_spec', '1.5.0'
  #gem 'selenium-webdriver', '2.0.0'
  #gem 'capybara', '2.1.0'
end

group :doc do
  gem 'sdoc', '0.3.20', require: false
end

app/controllers/application_controller.rb 的第4行是什么? - Chris Peters
复制了我的应用程序控制器。 - Derek
想知道为什么被接受的答案比得到赞同票的答案更好地解释了错误吗? - zeantsoi
2个回答

3

看起来你需要在第四行加一个空格。

所以

protect_from_forgery with::exception

变成:

protect_from_forgery with: :exception

原因是protect_from_forgery是一个方法,它期望它的唯一参数是一个哈希值。

2

ApplicationController 中的语法有误。Ruby 1.9.3 语法规定,当值为符号时,键和值之间必须有一个空格:

# apps/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

另一种方法是使用传统的hash-rocket语法:

protect_from_forgery :with => :exception

更新:

protect_from_forgery with::exception的问题源于protect_from_forgery期望其参数为哈希值。然而在Ruby中,双冒号::表示命名空间。基本上,ActionController认为with::exception是一个变量/方法,名为exception,并且这个变量/方法是在名为with的变量/方法内部的命名空间中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接