【问题标题】:Rails 5 Namespace need (in controller) or not (in model) to specify module nameRails 5 命名空间需要(在控制器中)或不需要(在模型中)指定模块名称
【发布时间】:2016-09-22 16:05:11
【问题描述】:

在同一模块内的模型中(app/models/oc/pedido.rb 和 app/models/oc/encuadernacion_papel.rb)

我可以在 pedido.rb 中做到这一点:

class Oc::Pedido < ActiveRecord::Base

  has_many :encuadernaciones_papel, class_name: "EncuadernacionPapel"

--> class_name 中没有“Oc::”:has_many :enc... class_name: "Oc::EncuadernacionPapel"

所以,Rails 理解 EncuadernacionPapel 在 Oc 模块中

我想在调用 Pedido 类时在“Oc”控制器中省略“Oc::”模块名称,但它会崩溃:

app/controllers/oc/firmas_controller.rb

class Oc::LiquidacionController < ApplicationController

    Pedido.find(...

我必须指定:

Oc::Pedido.find(...

为什么?这个对吗?还是我错过了什么?

非常感谢

【问题讨论】:

  • 这是由于 ruby​​ 中嵌套和持续查找的工作方式。 cirw.in/blog/constant-lookup.html
  • 感谢您的回复,嗯,我读过这样的帖子,我想我理解模型嵌套等等,但我认为 Rails 应用程序控制器和模型可能共享相同的模块......或者我应该在模型和控制器中做“Oc”的阳极模块父级吗?
  • 如果您将控制器声明为module Occlass LiquidacionController,它将从Oc 模块中查找Pedido

标签: ruby-on-rails namespaces


【解决方案1】:

如果您在重新打开模块时尝试使用快捷方式:

class Oc::LiquidacionController
  def show
    @pedido = Pedio.find(params[:id])
  end
end

您将收到NameError: uninitialized constant Oc::LiquidacionController 错误,因为Oc 不在Module.nesting 中。这是因为跳过的外部命名空间没有添加到Module.nesting

如果您改为使用“速记”形式:

module Oc
  class LiquidacionController
     def show
        @pedido = Pedio.find(params[:id])
        logger.info( Module.nesting.inspect )
     end
  end
end

Module.nesting 会给你[Oc::LiquidacionController, Oc]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 2017-03-21
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2017-07-15
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多