繁体   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