Search code examples
ruby-on-railsrubyruby-on-rails-3models

A model with a handful of id's


I have a model which has many of another model but this model only needs to have 10 or less id's in it.

Let's say it has, Bathroom, Kitchen, LivingRoom for arguments sake and the new records will probably never need to change.

What is the best way of making a model like this that doesn't use a database table?


Solution

  • Even though the collection of rows never changes, it's still useful to have this as a table in your database in order to leverage ActiveRecord relations. A less contrived example would be a database table that has a list of US states. This is highly unlikely to change, and would likely have only a couple of columns (state name and state abbreviation). However, by storing these in the database and supporting them with ActiveRecord, you preserve the ability to do handy things like searching for all users in a state using conventional rails semantics.

    That being said, an alternative would be to simply create a class that you stick in your models directory that does not inherit from ActiveRecord, and then either populate it once from the database when the application loads, or simply populate it by hand.

    A similar question was asked yesterday, and one of the answers proposes a mechanism for supporting something similar to what you want to do:

    How to create a static class that represents what is in the database?