最佳实践:我应该对静态数据使用 AR 模型还是全局哈希? [英] Best practice: should I use an AR Model or a global Hash for static data?
问题描述
我在考虑建立一个社交网站.我的用户模型应该有一个属性eyecolor",它可以在带有选择框/下拉列表的视图页面上设置.
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.
我的问题:-> 我应该制作 AR 模型还是应该对数据使用全局散列/常量?静态模型"有最佳实践吗?
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"?
以及如何将没有 AR 模型的关注与关系关联起来:
And how do I associate following without an AR-Model with relations:
u = User.first
u.eyecolor
==> 1 (not the eyecolor-string!)
我需要的是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
注意:此模型不是 Active Record 模型,但它确实创建了您尝试建模的真实世界对象的抽象.
Note: this model is not an Active Record model, but it does create an abstraction the real-world object you are trying to model.
我也喜欢这种方法,而不是全局散列,因为它可以在 EyeColor 内组织您的静态定义,而不是在您的程序中浮动,这使得该定义的位置很清楚.
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 %>
为谓词方法添加了问号.
added question mark to predicate method.
这篇关于最佳实践:我应该对静态数据使用 AR 模型还是全局哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!