回报率:MyModel.descendants在第一次通话后视图返回[]? [英] RoR: MyModel.descendants returns [] in a view after the first call?
问题描述
我要显示在视图中为MyModel子类的选择列表。它不工作呢,所以理智的检查,我包括这在我的观点:
I want to display a selection list of MyModel subclasses in a view. It's not working yet, so for sanity checking, I included this in my view:
<%= MyModel.descendants %>
在第一的时候,我渲染后重新启动服务器这个页面,它显示后裔的名单(有六个)。所有的以后的时候,它显示为空列表 []
。
The first time I render this page after re-starting the server, it shows the list of descendants (there are six). All subsequent times, it shows up as an empty list []
.
FWIW,我有我的初始化一个要求
语句:
FWIW, I have a require
statement in my initializers:
Dir[Rails.root.join("app/models/my_models/**/*.rb").to_s].each {|f| require f}
...我已经验证了他们得到必需的。
... and I've verified that they're getting required.
什么是@($%&放大器;?是怎么回事
What the @($%& is going on?
推荐答案
当您使用需要,即使你的 my_model.rb
被重新加载,内核不会要求你的子类 .RB
文件,因为它们已经被加载。你必须要经过导轨自动加载。
When you use require, even if your my_model.rb
gets reloaded, the kernel won't require your subclasses .rb
files because they have already been loaded. You'd have to go through rails autoload.
基本上,你的第一个要求,轨道自动加载为MyModel
从 my_model.rb
,然后要求 my_models / sub_model.rb
。该子模型
类继承为MyModel
,其中填充的后裔
阵列。
在你的下面的请求,不过,导轨自动加载为MyModel
试(嘿嘿,你是在开发模式),然后要求 my_models / sub_model.rb
了。但是这一次,内核知道它已经加载该文件,并不会再加载它。
Basically, on your first request, rails autoloads MyModel
from my_model.rb
, which then requires my_models/sub_model.rb
. The SubModel
class inherits MyModel
, which populates the descendants
array.
On your following requests, though, rails autoloads MyModel
again (hey, you're in dev mode), which then requires my_models/sub_model.rb
again. But this time, the kernel knows it had already loaded this file and won't load it again.
我一小时前就遇到了这个问题,这导致我到您的文章,并找到解决的办法。我们需要的是导轨自动加载的子类,每次你的主类调用。
I ran into this problem one hour ago, which lead me to your post, and to find a solution. What we need is rails to autoload subclasses everytime your main class is called.
下面是一个解决方案:
class MyModel
Dir[File.join(File.dirname(__FILE__),"my_models","*.rb")].each do |f|
MyModels.const_get(File.basename(f,'.rb').classify)
end
end
这些线路很可能是类的外放。这应该是足够(这是对我来说),如果你只有在 my_models
文件,而不是在子目录中。如果你有一些(例如 MyModels ::汽车::福特
,你可能需要把同样的东西在的子模块(在 my_models /car.rb
)。
These lines could probably be put outside of the class. That should be enough (it is for me) if you only have files in my_models
and not in subdirectories. If you have some (for example MyModels::Car::Ford
, you may need to put the same kind of stuff in the submodules (in my_models/car.rb
).
这篇关于回报率:MyModel.descendants在第一次通话后视图返回[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!