[英]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.