将rails app转换为引擎:使用命名空间调用关联

时间:2012-11-11 13:19:39

标签: ruby-on-rails associations

我正在尝试将https://github.com/ari/jobsworth转换为引擎(我暂时称之为scheduler)。其中一项工作是在主应用程序的User和引擎中的模型之间建立关联。

我在this answer中使用acts_as_scheduler_user

require "scheduler/engine"

module Scheduler    

module ActsAsSchedulerUser

   module ClassMethods

       def acts_as_scheduler_user(options = {})   
           has_many    :widgets
       end
#etc

新生引擎连接到我的主应用程序,当我在引擎代码或主应用程序代码中调用User.reflect_on_all_associations(:has_many)时,我成功获取

#<ActiveRecord::Reflection::AssociationReflection:0x000001069e45b0 @macro=:has_many, @name=:widgets, @options={:order=>"widgets.column, widgets.position", :dependent=>:destroy, :extend=>[]}, @active_record=User(id: integer, email: string, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: string, last_sign_in_ip: string, confirmation_token: string, confirmed_at: datetime, confirmation_sent_at: datetime, created_at: datetime, updated_at: datetime, first_name: string, last_name: string, client_id: integer, invitation_token: string, invitation_sent_at: datetime, invitation_accepted_at: datetime, invitation_limit: integer, invited_by_id: integer, invited_by_type: string, client_name_requested: string, mode: string, forem_admin: boolean, forem_state: string, forem_auto_subscribe: boolean), @plural_name="widgets", @collection=true> 

current_user在引擎应用中工作正常 - 返回主应用的current_user。

但是,当我在引擎的应用中调用current_user.widgets时,我收到错误uninitialized constant User::Widget

有什么想法?

++++++++++

编辑:啊,当我在控制台中Widget.all时,我得到NameError: uninitialized constant Widget,但当我Scheduler::Widget.all时,我得到了正确的答案。所以我现在的问题是如何在使用命名空间时调用current_user.widgets

1 个答案:

答案 0 :(得分:1)

我可能会忽略这一点(对引擎没有多少经验),但也许只是将实际类传递给has_many类方法以包含命名空间。

def acts_as_scheduler_user(options = {})   
  has_many :widgets, :class_name => Scheduler::Widget
end