Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 Rails 3-多态模型需要共享模型方法_Ruby On Rails 3_Activerecord_Shared Libraries_Polymorphic Associations - Fatal编程技术网

Ruby on rails 3 Rails 3-多态模型需要共享模型方法

Ruby on rails 3 Rails 3-多态模型需要共享模型方法,ruby-on-rails-3,activerecord,shared-libraries,polymorphic-associations,Ruby On Rails 3,Activerecord,Shared Libraries,Polymorphic Associations,目前,我在多个模块中重复了如下代码: def do_something_polymorphic self.something_polymorphic_able.where(.....).each do |thing| ... end end 本着DRY的精神,我尝试将do\u something\u polymorphic()移动到/lib/shared\u methods.rb的模块中。在我的模型中添加include SharedMethods时,我得到一个错误: unini

目前,我在多个模块中重复了如下代码:

def do_something_polymorphic
  self.something_polymorphic_able.where(.....).each do |thing|
    ...
  end
end
本着DRY的精神,我尝试将
do\u something\u polymorphic()
移动到
/lib/shared\u methods.rb
的模块中。在我的模型中添加
include SharedMethods
时,我得到一个错误:

uninitialized constant Chapter::SharedMethods (NameError)
我不知道该怎么走

然后我尝试将模块文件加载到模型中(
load'shared\u methods.rb'
)。它加载了OK,但是模块构造抛出了名称空间,并且对于加载/包含它的模型,
do\u something\u polymorphic()
没有定义。因此,如果您试图自引用对象,“模块”似乎不是一个选项

最后,我从shared_methods.rb文件中删除了模块构造,只在文件中保留了do_something_polymorphic()方法。它加载正常,但当我运行该方法时,出现了错误:

NoMethodError: private method `do_something_polymorphic' called for #<Polymorphic_Object:0x007fc27e5b8338>
NoMethodError:调用私有方法'do\u something\u polymorphic'#
不知道从这里到哪里去。我可以将其设置为一个模块,并尝试将“self”作为对象参数传递给该方法,但我希望保留对其对象干净地调用该方法的能力:
current\u object.do\u多态性


除了继承路径(我真的想避免),还有没有一种方法可以跨多个模型共享一个使用
self
关键字的方法?

您可以通过修改应用程序配置自动包含lib/模块

#config/application.rb

config.autoload_paths += %W(#{config.root}/lib)

谢谢你,萨利尔。这解决了“包括SharedMethods”的问题。这反过来又解决了另一个问题。我现在可以从所有不同的对象类型中调用do_something_多态()方法。这使一切都很好和干燥!再次感谢。