Creating a gem with associated Rails models

I would like to package a gem that includes ActiveRecord models that can be associated with models in the existing Rails application. I've been trying to follow the code for acts_as_taggable_on, but I'm running into some problems getting the associations to work.

My gem is called Kitchen. My model defined in the gem is Dish, and I want to add a polymorphic association (as Cook) to a model in the main application such as User.

In lib/kitchen.rb

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

In lib/kitchen/dish.rb

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

In lib/kitchen/cook.rb (lifting code from http://guides.rubyonrails.org/plugins.html#add-an-acts_as-method-to-active-record without much understanding)

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

Finally, I've migrated everything in my dummy app, and include the association in spec/dummy/app/models/user.rb

class User < ActiveRecord::Base
  acts_as_cook
end

I'm getting an error any time I try to access user.dishes for a User instance:

 NameError:
   uninitialized constant User::Dish

Any idea what's missing?


尝试这可能:

has_many :dishes, :as => :cook, :class_name => 'Kitchen::Dish'
链接地址: http://www.djcxy.com/p/14248.html

上一篇: 如何在gem中运行Rails应用程序?

下一篇: 用关联的Rails模型创建一个gem