簡體   English   中英

Rails:如何擴展gem的ActiveRecord子類?

[英]Rails: how to extend a gem's ActiveRecord child class?

我在擴展一個在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

我實際上將該模塊直接放入沙發的初始化器中。 希望這可以幫助。

跳出來的最明顯的事情就是你說你“試圖從舒適的墨西哥沙發插件中擴展Site類”

...但是模塊中的類正在擴展ActiveRecord :: Base。

module Cms    
  class Site < ActiveRecord::Base
  ...

也許我讀錯了,但聽起來你的課應該是這樣的:

module Cms      
  class Site < CmsSite  // i.e. extending the class from comfortable-mexican-sofa
  ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM