if defined? MyModel # do stuff with MyModel end
It appears that this does not always work as I had intend. I am seeing "defined? MyModel" returning nil when the check is performed in development and test modes if it runs before the model has been used. I think the code below is a minimal example to show what I'm getting. I have not seen this problem when running the app in production, so perhaps there is some lazy loading going on?
- What is the best way to check a model exists?
- If using defined? is correct and works in production, how should I test the code? At the moment within my rspec feature tests, the call to "defined? MyModel" in the templates returns nil, so additional functionality is not included in the page.
$ rails new test_model_exists $ cd test_model_exists $ rails generate model MyModel $ bundle exec rake db:migrate $ bundle exec rails console Loading development environment (Rails 4.0.0) 2.0.0-p247 :001 > defined? MyModel => nil 2.0.0-p247 :002 > MyModel => MyModel(id: integer, created_at: datetime, updated_at: datetime) 2.0.0-p247 :004 > defined? MyModel => "constant"