Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: should I use an AR Model or a global Hash for static data?

I'm thinking about a social networking-site. My user-model should have an attribute "eyecolor", which could be set on a view-page with a select-box/dropdownlist.

My question: -> should I make a AR-Model or should I use a global Hash/Constant for the data? Is there a best practice for "static-models"?

And how do I associate following without an AR-Model with relations:

u = User.first 
u.eyecolor 
==> 1 (not the eyecolor-string!)

What I need is the eyecolor-string:

u = User.first 
u.eyecolor 
==> "brown"

Thanks, sorry for my bad english!

like image 921
BvuRVKyUVlViVIc7 Avatar asked Mar 05 '09 14:03

BvuRVKyUVlViVIc7


2 Answers

You could create a model to handle your eye-color logic:

class EyeColor
   COLORS = ['blue','brown','hazel']

   attr_accessor :color

   # Some logic methods...
   def is_brown?
     self.color == 'brown'
   end

end

Note: this model is not an Active Record model, but it does create an abstraction the real-world object you are trying to model.

EDIT: I also like this approach as opposed to a global hash, because it gives it organizes your static definition within EyeColor instead of floating around in your program, which makes it clear where this definition is.

<%= select :user, :eye_color, EyeColor::COLORS %>

EDIT: added question mark to predicate method.

like image 104
berlin.ab Avatar answered Nov 17 '22 01:11

berlin.ab


What you want is a Constant. I put these in a file in config/initializers/constants.rb; that way they are all in the same place.

EyeColors = %w{Blue Brown Hazel Green}

In your form just do:

<%= f.select :eye_color, EyeColors %>
like image 42
Matt Darby Avatar answered Nov 17 '22 00:11

Matt Darby