`Describe table` showing up on each Rails request
I've got 2 m开发者_开发百科odels, band
and genre
, and a many-to-many relation via an association table bands_genres
(which doesn't have a model) the following way.
class Genre < ActiveRecord::Base
has_and_belongs_to_many :bands
class Band < ActiveRecord::Base
has_and_belongs_to_many :genres
Checking out the output logs of my app, I see that every call involving bands or genres end up doing this query:
SQL (1.8ms) describe `bands_genres`
Why is this happening? How could I cache somehow the result of this query to avoid doing it on each request?
Run your server in production mode. Table information is reloaded on each request when in development mode.
rails s -e production
It's because your current environment configuration tells Rails to do so. I assume you use "development", but you do have "production", and "test" also.
There is an option to cache classes in any of your envs' configuration. Check the current one (I assume you use "development"):
config/environments/development.rb
and modify this option to true
:
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = true
Then, run server with your current environment. For development:
bundle exec rails s
is enough.
This does 2 things:
1) when Rails start, it will now read all classes' definitions
(models) up front, and keep it for each request.
When you change a class now, no code will be reloaded automatically
2) Rails will not ask database for model metadata change,
so no "describe table" will go to database in any request
"Production" env by default has this option set to "true". But "production" env is meant for production and not development. You may specify different options, urls, vars there..
精彩评论