Rails 3: What's the correct Rails way to create custom types?

I'm currently tinkering with a fairly complex Ruby on Rails model, and I was wondering what is the correct "Rails" way to do custom types for attributes. For example, I have a table businesses

that has a string attribute region

. But the region can be only one of the predefined lists of possibilities (which can be later expanded). My question is, where can I define this type of region?

I know I can create a specific table regions

(i.e. a region model) in which all the parameters could be placed, and then I could establish a relationship between the models having regions for that table. The problem is that I have many of these types in my model, so I end up with over half of the tables in my database that are "custom type tables" that only store possible values ​​for those types. Is it practical?

I also read that you can do this with validation (that is, check when saving the record that the variables are within their possible values). This seems very impractical, as I want this model to expand and the submission has to load the possible values ​​of the types into separate fields, etc. If I were to use this method, every time I needed to add a new possible value for a type, I would have to change the validation and views.

Is there a standard way to do something like this? Something like defining types (maybe models without DB support?) Where I could easily list all the possible values?

Thanks for any help or suggestions on this. This has bothered me for a long time when I make RoR apps and I'm tired of hacking.

+3


source to share


1 answer


I think there are many different ways to do this. Personally, I will keep things very simple and dry.

In the initializer, set the arrays in the global scope:

REGIONS = ["region A", "region B", "region C"]

      



In models, use validations as you wrote. Make sure the value is in the array REGIONS

.

In views, use Rails helpers to populate selections, radio stations, etc. from an array REGIONS

. If you always have the same selection, write your own sub region_select for example.

+1


source







All Articles