我想打包一个 gem,其中包含可以与现有 Rails 应用程序中的模型相关联的 ActiveRecord 模型。我一直在尝试遵循 acts_as_taggable_on 的代码,但在让关联正常工作时遇到了一些问题。
我的 gem 叫做 Kitchen。我在 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
最后,我迁移了虚拟应用中的所有内容,并将关联包含在 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'
关于ruby-on-rails - 使用关联的 Rails 模型创建 gem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9182299/