首先,抱歉标题不好,无法想出更具描述性的内容。
我有一个用户模型。我想为该用户设置一个类型,可以是 5 个选项之一;无论选项是什么,任何字符串都可以。我希望能够根据这些选项进行搜索。
我想我有以下选项:
- 将字段作为字符串添加到带有索引的模型中
- 创建一个 user_type 表并执行 own_to/has_many 关系
- 将类型保存为整数并将整数映射到用户模型中定义的常量,并带有字符串值(不知道该怎么做不过)
解决这个问题的Rails Way方法是什么,它将满足以下目标:
谢谢
First, sorry for bad title, couldn't come up with something more descriptive.
I have a user model. I'd like to set a type for that user which can be one of 5 options; doesn't matter what the options are, any strings will do. I'd like to be able to search based on these options.
I think I have the following options:
- Added field as string to model with index
- Create a user_type table and do belongs_to/has_many relationship
- Save type as integer and map integer to a constant defined in user model, with string value (no idea how to do this though)
What's the Rails Way to solve this problem that will meet the following goals:
- Searchable
- Maintainable
- Readable
Thank you
发布评论
评论(2)
我会选择选项 #2,它可以让您动态添加用户类型,而无需接触代码。如果将来您想让一个用户同时具有多种不同类型,请查看 has_and_belongs_to_many
I'd go with option #2, that will let you dynamically add user types without touching code. If in the future, you want to let a user be more than different types simultaneously, check out has_and_belongs_to_many
这确实取决于您对“类型”的含义。如果它是一个角色(例如“管理员”、“主持人”、“用户”等),其中给定用户只能属于一种类型,则可以使用字符串列来完成此操作 -不需要单独的表。
如果用户可以同时属于多种类型(“新注册”、“男性”、“学生”、“博主”),其中用户类型更像标签,那么您的
user_type
表将完成这项工作。This really does depend on your meaning of 'type'. If it's a role (such as "administrator", "moderator", "user", etc.) where a given user can only be of one type, you can just do it with a string column - no need for a separate table.
If the user can be multiple types simultaneously ("newly-registered", "male", "student", "blogger"), where the user type works more like a tag, then your
user_type
table will do the job.