简体   繁体   English

从命名空间控制器中访问Rails Engine模型

[英]Accessing a Rails Engine model from within a namespaced controller

I have Rails Engine model that looks something like this: 我有看起来像这样的Rails Engine模型:

module Adhocracy
  class Membership < ActiveRecord::Base
  . . .
  end
end

So I would expect to be able to access it with Adhocracy::Membership . 因此,我希望能够通过Adhocracy::Membership访问它。 However, I'm getting an error in this namespaced controller: 但是,此命名空间控制器出现错误:

module Api
  module V1
    class Adhocracy::MembershipsController < ApplicationController
      def index
        @memberships = Adhocracy::Membership.where(params)
      end
    end
  end
end

The error is: 错误是:

uninitialized constant Api::V1::Adhocracy::Membership

If I go into this controller with debugger and type in Adhocracy , it returns Api::V1::Adhocracy , while Adhocracy::Membership returns the above error. 如果我进入带有调试器的控制器并输入Adhocracy ,它将返回Api::V1::Adhocracy ,而Adhocracy::Membership返回上述错误。 However, if I go into another controller with debugger (such as Api::V1::SessionsController ), Adhocracy::Membership returns the expected model. 但是,如果我使用调试器进入另一个控制器(例如Api::V1::SessionsController ),则Adhocracy::Membership将返回预期的模型。 Any idea what's going on? 知道发生了什么吗?

Its due to how Ruby works: it first searches in your current classes, then in its ancestors. 它是由于Ruby的工作原理而产生的:它首先在您当前的类中搜索,然后在其祖先中搜索。

So Adhocracy matches Api::V1::Adhocracy in your MembershipsController and it searches Membership there. 因此, Adhocracy在您的MembershipsController匹配Api::V1::Adhocracy ,并在其中搜索Membership

Whereas in another controller with no match, the search goes down the ancestor tree until it reaches Object where Adhocracy is defined. 而在另一个没有匹配项的控制器中,搜索沿着祖先树向下进行,直到到达定义了Adhocracy Object

To be sure to get top level constants append :: which leads you to: ::Adhocracy::Membership 为确保获取顶级常量,请附加::导致::Adhocracy::Membership

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM