簡體   English   中英

使用關聯的Rails模型創建gem

[英]Creating a gem with associated Rails models

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

我的寶石叫做廚房。 我在gem中定義的模型是Dish,我想在主應用程序(如User)中為模型添加多態關聯(作為Cook)。

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

最后,我已經在我的虛擬應用程序中遷移了所有內容,並在spec/dummy/app/models/user.rb包含該關聯

class User < ActiveRecord::Base
  acts_as_cook
end

我在嘗試訪問User實例的user.dishes時遇到錯誤:

 NameError:
   uninitialized constant User::Dish

知道缺少什么嗎?

試試吧:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM