简体   繁体   中英

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM