2012-02-07 50 views
3

我想打包一個包含ActiveRecord模型的gem,該模型可以與現有Rails應用程序中的模型關聯。我一直在試圖遵循acts_as_taggable_on的代碼,但我遇到了一些讓協會工作的問題。使用關聯的Rails模型創建gem

我的寶石被稱爲廚房。我在gem中定義的模型是Dish,並且我希望將一個多態關聯(如Cook)添加到主應用程序(例如User)中的模型中。

lib/kitchen.rb

require "active_record" 
require "kitchen/dish.rb" 
require "kitchen/cook.rb" 

lib/kitchen/dish.rb

module Kitchen 
    class Dish < ::ActiveRecord::Base 
    belongs_to :cook, :polymorphic => true 
    end 
end 

lib/kitchen/cook.rb(從提升代碼http://guides.rubyonrails.org/plugins.html#add-an-acts_as-method-to-active-record沒有太多的理解)

module Kitchen 
    module Cook 
    extend ActiveSupport::Concern 

    included do 
    end 

    module ClassMethods 
     def acts_as_cook 
     class_eval do 
      has_many :dishes, :as => :cook 
     end 
     end 
    end 
    end 
end 

ActiveRecord::Base.send :include, Kitchen::Cook 

最後,我在我的虛擬遷移的一切一個PP,並且包括在spec/dummy/app/models/user.rb

class User < ActiveRecord::Base 
    acts_as_cook 
end 

我得到一個錯誤,任何時候,我嘗試訪問user.dishes爲用戶實例的關聯關係:

NameError: 
    uninitialized constant User::Dish 

任何想法,缺少了什麼?

回答

3

試試這個可能:

has_many :dishes, :as => :cook, :class_name => 'Kitchen::Dish' 
+0

真棒,即固定的錯誤。現在,當我嘗試使用'user.dishes'做任何事情時,都會給我一個錯誤: NoMethodError:undefined方法X for Kitchen :: Cook:模塊 – 2012-02-07 19:30:04

+0

沒關係,我剛剛從玩具領域翻譯過來,感到困惑。你的答案完全有效。 – 2012-02-07 23:55:21