nullnullnull
nullnullnull

Reputation: 8189

Accessing a Rails Engine model from within a namespaced controller

I have Rails Engine model that looks something like this:

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

So I would expect to be able to access it with 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. However, if I go into another controller with debugger (such as Api::V1::SessionsController), Adhocracy::Membership returns the expected model. Any idea what's going on?

Upvotes: 0

Views: 71

Answers (1)

apneadiving
apneadiving

Reputation: 115541

Its due to how Ruby works: it first searches in your current classes, then in its ancestors.

So Adhocracy matches Api::V1::Adhocracy in your MembershipsController and it searches Membership there.

Whereas in another controller with no match, the search goes down the ancestor tree until it reaches Object where Adhocracy is defined.

To be sure to get top level constants append :: which leads you to: ::Adhocracy::Membership

Upvotes: 1

Related Questions