如何在 Rails 模型中编写类级方法,以便它们不会在 rake 任务期间执行?
我在 Rails 应用程序中有一个角色模型,我在其中编写了一些快速快捷方式类方法。这些方法本质上只是一些常用查找器的方便包装。但这带来了一个严重的问题。如果我尝试使用干净的数据库在另一台计算机上加载该应用程序的架构,那么它将失败。这是因为 db:schema:load rake 任务首先加载整个 Rails 环境,从而加载我的类方法,这些方法正在数据库中查找记录,当然,该记录尚不存在。
所以有两个问题:
- 我不知道我理解为什么它在加载时运行该方法。
- 除非我挽救每种方法的错误,否则我不知道有什么解决办法。
我是否缺少“rails”或“ruby”方式?
这是我的示例代码:
Class Role < ActiveRecord::Base
def self.admin
find_by_name "Administrator"
end
def self.user
find_by_name "User"
end
def self.moderator
find_by_name "Moderator"
end
end
要点相同的代码: https://gist.github.com/836501
感谢您的帮助。
更新:
事实证明,我忘记将对这些类方法的调用从我的工厂放在块的一侧。
所以这个:
Factory.define :admin, :parent => :user do |f|
f.roles [Role.admin]
end
需要是这样:
Factory.define :admin, :parent => :user do |f|
f.roles {[Role.admin]}
end
I have a roles model in a rails app that I have written a few quick shortcut class methods in. These methods are essentially just convenience wrappers for some commonly used finders. But this presents a serious problem. If I try to load the schema for that app on another computer with a clean database, then it will fail. This is due to the fact that the db:schema:load rake task loads the entire rails environment first, thus loading my class methods which are looking for a record in a database that, of-course, doesn't yet exist.
So two problems:
- I don't know that I understand why it runs the method on load.
- I don't know any way around it unless I rescue errors for every method.
Is there a 'rails' or 'ruby' way that I am missing?
Here's my example code:
Class Role < ActiveRecord::Base
def self.admin
find_by_name "Administrator"
end
def self.user
find_by_name "User"
end
def self.moderator
find_by_name "Moderator"
end
end
And the same code in a gist: https://gist.github.com/836501
Thanks for any help.
UPDATE:
It turned out that I forgot to place the calls to these class methods from my factories in side of a block.
So this:
Factory.define :admin, :parent => :user do |f|
f.roles [Role.admin]
end
Needs to be this:
Factory.define :admin, :parent => :user do |f|
f.roles {[Role.admin]}
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的错误不在于这些类方法,它们不会自行执行,而在于您如何调用它们。
如果您在其他地方的初始化代码或模型代码中调用 Role.admin、Role.user 等,它将执行这些作用域。
我建议在您的代码库中搜索这些内容的参考。
此外,如果您发布错误的堆栈跟踪(当数据库尚未填充时),它可能会提供是谁在调用这些错误的线索。
The error here isn't with these class methods, which won't execute on their own, but how you're calling them.
If you're calling Role.admin, Role.user, etc in initialization code or model code elsewhere it will execute these scopes.
I would recommend searching your codebase for references to these.
Additionally, if you post the stack trace of the error (when the DB isn't populated yet) it may provide a clue to who's calling these.