views:

78

answers:

1

my sql DB contains tables "jobs" and "job_categories."

"job_categories" associates job category strings (i.e. "Software Development") with an integer number (i.e. 7).

I need these associations saved into variables in my job controller for various query functions. How can I use rails to dynamically link changes to the job_categories table to variables in my jobs controller? I've worked with RoR for a few weeks now but am still a little fuzzy on how everything interacts. Thank you!

+3  A: 

There's one big gotcha with what you're trying to do, but first I'll answer your question as asked.

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.

class JobsController < ActionController::Base
  @@categories = JobCategory.find(:all)
  cattr_accessor :categories

  # ...
end

class JobCategoryObserver < ActiveRecord::Observer
  def after_save(category)
    JobsController.categories[category.name] = category.id
  end

  def after_destroy(category)
    JobsController.categories.delete(category.name)
  end
end

You'll need additional logic that removes the old name if you allow for name changes. The methods in ActiveRecord::Dirty will help with that.

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 job_categories table, but that change only is updated in one process. The others are now stale.

Your job_categories 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 JobsController anyway.

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.

Steve Madsen