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!
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.
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With