【问题标题】:Routing error undefined local variable or method `with' for ApplicationController:ClassApplicationController:Class 的路由错误未定义局部变量或方法“with”
【发布时间】:2013-09-09 23:21:18
【问题描述】:

我对 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

也许是什么宝石吓坏了?

宝石文件:

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 行有什么内容?
  • 粘贴了我的应用控制器
  • 好奇接受的答案如何比赞成的答案更好地解释错误?

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

看起来你需要在第 4 行留一个空格。

所以

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
    

    另一种方法是使用传统的哈希火箭语法:

    protect_from_forgery :with => :exception
    

    更新

    protect_from_forgery with::exception 的问题源于protect_from_forgery 期望一个散列作为其参数。但是,在 Ruby 中,双冒号 :: 表示命名空间。基本上,ActionController 认为with::exception 是一个名为exception 的变量/方法,它位于一个名为with 的变量/方法中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      相关资源
      最近更新 更多