How do I write class level methods in rails models so they don't get executed during rake tasks?
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开发者_StackOverflow 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
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.
精彩评论