我在扩展一个在gem中定义的类并且是ActiveRecord :: Base的子类时遇到了问题.
我唯一想扩展这个类的是:
has_many:promos
然而,扩展倾向于排除原始类.我得到的错误:
PGError: ERROR: relation "sites" does not exist LINE 4: WHERE a.attrelid = '"sites"'::regclass ^ : SELECT a.attname,format_type(a.atttypid,a.atttypmod),d.adsrc,a.attnotnull FROM pg_attribute a LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum WHERE a.attrelid = '"sites"'::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum
检查控制台中的类给出:
Cms::Site(Table doesn't exist)
set_table_name :cms_sites
顺便说一句.我正在尝试从comfortable_mexican_sofa插件扩展Site类.
这是应该扩展类的文件:
# lib/comfortable_media_sofa/comfortable_media_sofa.rb require 'comfortable_mexican_sofa' module Cms class Site < ActiveRecord::Base has_many :promos end end
在这里加载:
require File.expand_path('../boot',__FILE__) require 'rails/all' Bundler.require(:default,Rails.env) if defined?(Bundler) module Mkturbo class Application < Rails::Application config.autoload_paths += %W(#{config.root}/vendor/gems/comfortable_mexican_sofa-0.0.18) config.autoload_paths += %W(#{config.root}/lib/comfortable_media_sofa) config.plugins = [ :comfortable_mexican_sofa,:comfortable_media_sofa,:all ] # .... end end
并且在comfortable_mexican_sofa初始化程序的顶部是必需的:
# config/initializers/comfortable_mexican_sofa.rb require 'comfortable_media_sofa'
我怎样才能做到这一点?是需求订单问题还是我以错误的方式扩展?提前谢谢了!
解决方法
在你的例子中,你完全覆盖了那个类.你只需要把东西注入其中……就像这样:
module MyModule def self.included(base) base.has_many :things end end Cms::Site.send(:include,MyModule)
然后只是看看关联是否开始:
ruby-1.9.2-p180 :005 > s = Cms::Site.new => #<Cms::Site id: nil,label: nil,hostname: nil> ruby-1.9.2-p180 :006 > s.things NameError: uninitialized constant Cms::Site::Thing
我实际上将该模块直接放入沙发的初始化程序中.希望这可以帮助.