Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's one big gotcha with what you're trying to do, but first I'll answer your question as asked.</p> <p>Create class-level accessors in your JobsController, then write an Observer on the JobCategory class that makes the appropriate changes to the JobsController after save and destroy events.</p> <pre><code>class JobsController &lt; ActionController::Base @@categories = JobCategory.find(:all) cattr_accessor :categories # ... end class JobCategoryObserver &lt; ActiveRecord::Observer def after_save(category) JobsController.categories[category.name] = category.id end def after_destroy(category) JobsController.categories.delete(category.name) end end </code></pre> <p>You'll need additional logic that removes the old name if you allow for name changes. The methods in <a href="http://apidock.com/rails/ActiveRecord/Dirty" rel="nofollow noreferrer">ActiveRecord::Dirty</a> will help with that.</p> <p>So, the gotcha. The problem with an approach like this is that typically you have more than one process serving requests. You can make a change to the <code>job_categories</code> table, but that change only is updated in one process. The others are now stale.</p> <p>Your <code>job_categories</code> table is likely to be small. If it's accessed with any frequency, it'll be cached in memory, either by the OS or the database server. If you query it enough, the results of that query may even be cached by the database. If you aren't querying it very often, then you shouldn't be bothering with trying to cache inside <code>JobsController</code> anyway.</p> <p>If you absolutely must cache in memory, you're better off going with memcached. Then you get a single cache that all your Rails processes work against and no stale data.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload