ruby-on-rails - 与 rails 中的模块和型号名称混淆

标签 ruby-on-rails ruby namespaces

我为 Customer 实现了完整的 CRUD 系统在项目中。 customers_controller.rb 的路径是

app/controllers/admin/customers_controller.rb

最重要的是,我必须添加新功能,所以我创建了一个新 Controller feature_controller.rb (名称已更改)具有这样的文件路径
app/controllers/admin/customer/features_controller.rb

Controller 内的代码
module Admin
  module Customer
    class FeatureController < ApplicationController
      def index; end
    end
  end
end

所以它对我的旧功能有一些影响,因为当我通常创建客户时,它报告了这个错误:
NoMethodError (undefined method `new' for Admin::Customer:Module):
  app/controllers/admin/customers_controller.rb:21:in `create'

第 21 行是:
@customer = Customer.new customer_params
if @customer.save
....

然后我删除了 新 Controller 和文件夹 但仍然是同样的错误。

我看了Customer的类型类(class)binding.pry并且说它是Module .

更新
development.rb
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

application.rb
config.autoload_paths += %W(#{config.root}/lib)
    config.autoload_paths += Dir["#{config.root}/lib/**/*"].select{|f| File.directory? f}

最佳答案

使用常量分辨率运算符 ( :: )。

@customer = ::Customer.new customer_params

会为你解决它,因为这样你会告诉 rails 寻找 Customer当前范围之外的常量。

关于ruby-on-rails - 与 rails 中的模块和型号名称混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42974546/

相关文章:

ruby - 在 Ruby 的 if 语句中检查 bash 命令

php - (PHP) 使用命名空间前缀附加新的 XML 子元素

ruby-on-rails - ActiveRecord虚拟属性作为记录属性

javascript - 将下拉菜单重置为选定值

ruby-on-rails - Rails 2 - partials : what does @comment = Comment. new 是什么意思?

namespaces - 仅向元素添加命名空间并更改为大写

php - 从不同的命名空间调用类

mysql - Ruby on Rails 无法连接到 mysql 数据库

ruby-on-rails - rails 3 : Working Mongoid captcha exists?

ruby - 递归 self 完善