我已经创建了一个简单的railtie,向ActiveRecord添加了一堆东西:
0 module Searchable
1 class Railtie < Rails::Railtie
2 initializer 'searchable.model_additions' do
3 ActiveSupport.on_load :active_record do
4 extend ModelAdditions
5 end
6 end
7 end
8 end在调用应用程序之前,我需要这个文件(在/lib中),方法是将以下行添加到配置/环境.rb中:
require 'searchable'这在我的应用程序中工作得很好,没有什么大的问题。
但是,我遇到了rake db:seed的问题。
在我的seeds.rb文件中,我从csv读取数据并填充数据库。我遇到的问题是,我对ActiveRecord所做的添加没有加载,并且seeds失败并出现了method_missing错误。我不会调用这些方法,但我假设由于seeds.rb加载了模型,它会尝试调用其中的一些方法,这就是它失败的原因。
谁能告诉我一个更好的地方来放置需求,以便每次加载ActiveRecord时(而不仅仅是整个应用程序加载时)都会包含它?我更喜欢将代码放在我的模型之外,因为它是我的大多数模型之间共享的代码,我想让它们保持干净和干燥。
发布于 2012-09-22 21:17:47
将扩展放在那里只是将其添加到ActiveRecord::Base。
当一个模型类被引用时,通过Rails 3.1自动加载/常量查找,它将加载该类。在这一点上,发生了什么,基本上是纯粹的Ruby (没有什么魔力)。所以我认为你至少有几个选择。“不好的”选项在某种程度上做了你想让它挂接到依赖加载中的事情。可能是这样的:
module ActiveSupport
module Dependencies
alias_method(:load_missing_constant_renamed_my_app_name_here, :load_missing_constant)
undef_method(:load_missing_constant)
def load_missing_constant(from_mod, const_name)
# your include here if const_name = 'ModelName'
# perhaps you could list the app/models directory, put that in an Array, and do some_array.include?(const_name)
load_missing_constant_renamed_my_app_name_here(from_mod, const_name)
end
end
end另一种方法是像您所做的那样使用Railtie,并向ActiveRecord::Base添加一个类方法,然后包含一些内容,如:
module MyModule
class Railtie < Rails::Railtie
initializer "my_name.active_record" do
ActiveSupport.on_load(:active_record) do
# ActiveRecord::Base gets new behavior
include ::MyModule::Something # where you add behavior. consider using an ActiveSupport::Concern
end
end
end
end如果使用ActiveSupport::Concern:
module MyModule
module Something
extend ActiveSupport::Concern
included do
# this area is basically for anything other than class and instance methods
# add class_attribute's, etc.
end
module ClassMethods
# class method definitions go here
def include_some_goodness_in_the_model
# include or extend a module
end
end
# instance method definitions go here
end
end然后在每个模型中:
class MyModel < ActiveRecord::Base
include_some_goodness_in_the_model
#...
end然而,这并不比只在每个模型中包含好多少,这是我推荐的。
https://stackoverflow.com/questions/8248122
复制相似问题