Rails global enums? -


I have items in my database schema that are integers and are set to a specific number corresponding to an item. For example, The column named appoint_type can set the value of 0 = unknown, 1 = medical, 3 = test, etc. ... I do not want to use magic number in my rail code and likes to like an envelope. Make satisfactory and readable addition, there is more than one table which These are the columns of this type of appointment, so I want to be able to use "enum" to address other columns too.

I was thinking of having a global enumeration, I have to use it in my model, controller and view. It may be less likely that I need to access it in my model, but surely within the controller and the scene.

Is there any good way to handle this?

It is likely to be low that I can access it in my model Required, but definitely in the controller and view.

Are you sure? When you talk about databases and schemas, you are talking about the model part of your application. I think the best place to store these variables will use those models that use them.

If these variables are related to a model, then you can put them in the model directly:

  class items & lt; ActiveRecord :: Base STATUS_UNKNOWN = 0 STATUS_MEDICAL = 3 end  

Then you can reference the value inside and outside the model scope

  class item def my_method STATUS_UNKNOWN end and item :: STATUS_UNKNOWN # = & gt; 0 items.New.Mi_Math # = & gt; 0  

When values ​​are calculated, rubians often use hash or arrays.

  class items AVAILABLE_STATUSES = {: unkwnown = & gt; 0,: Medicine = & gt; 3} DF self.statuses themselves AVAILABLE_STATUSES.keys.sort end def self.status_value (key) self.AVAILABLE_STATUSES [: Key] End end item: AVAILABLE_STATUS # = & gt; {: Unkwnown = & gt; 0,: Medicine = & gt; 3} Item.Stats # = & gt; [: Medicine ,: unkwnown] Item.status_value (: Medicine) # = & gt; 3 If more than one model shares the same logic, you can put it in a module and keep the module together in all the models it needs. 


Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -