Ruby on rails Rails 4中的非activerecord模型结构
我的尝试看起来像这样,带有继承的非activerecord模型。Ruby on rails Rails 4中的非activerecord模型结构,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我的尝试看起来像这样,带有继承的非activerecord模型。 app/models/matching_method.rb: class MatchingMethod attr_accessor :name end class LD < MatchingMethod end class Soundex < MatchingMethod end 对于每一类: class MatchingMethod::LD < MatchingMethod end 类匹配方法::L
app/models/matching_method.rb
:
class MatchingMethod
attr_accessor :name
end
class LD < MatchingMethod
end
class Soundex < MatchingMethod
end
对于每一类:
class MatchingMethod::LD < MatchingMethod
end
类匹配方法::LD
但是,这次MatchingMethod.substands
找不到
继承类不再存在
有什么建议吗?或者我应该重新设计这种方法。谢谢 Rails仅在您请求
MatchingMethod::ld
时加载ld.rb
。它通过const\u missing
解析类。您需要在代码中请求MatchingMethod::LD
,或者手动要求文件matching_method/LD.rb
。在类文件加载之前,MatchingMethod
不知道它的后代LD
:
MatchingMethod.descendants
# => []
MatchingMethod::LD
# => MatchingMethod::LD
MatchingMethod.descendants
# => [MatchingMethod::LD]
要从matching_method
dir加载所有类:
Dir['app/models/matching_method/*.rb'].each do |f|
require Pathname.new(f).realpath
end
要在不重新启动应用程序的情况下重新加载它们(如开发环境中的Rails loader):
它不会监视文件更改。保存更改后,您需要手动加载文件。而且它不会删除任何现有的方法/变量。它只会添加新的或更改现有的。谢谢!有没有办法自动加载这些子体方法?@PhatWangrungarun是的,Dir['app/models/matching_method/*.rb']。每个{f |都需要路径名。new(f).realpath}这非常有效,谢谢!但是,每次我在子类中进行一些更改时,我都需要重新启动应用程序以获得更改。这正常吗?好问题。您肯定想重新发明Rails:)将
require
更改为load
,并在每次更改后重复<代码>要求仅加载文件一次<代码>加载是相同的,但会一次又一次地重新加载。由于性能影响,没有人在生产环境中使用load
ii。
Dir['app/models/matching_method/*.rb'].each do |f|
require Pathname.new(f).realpath
end
Dir['app/models/matching_method/*.rb'].each do |f|
load Pathname.new(f).realpath
end