对于 Rails 3.0 Todo 应用程序,我有一个带有 Status 字段的任务模型。存储状态字段数据(字段类型)并仍然在 View (HTML 表)中显示人类可读版本的最佳方式是什么?状态可以是:
0 = 正常
1 = 活跃
2 = 完成
现在我有这个:
此处的 Rails 架构:
create_table "tasks", :force => true do |t|
t.integer "status", :limit => 1, :default => 0, :null => false
此处为 Rails 模型:
class Task < ActiveRecord::Base
validates_inclusion_of :status, :in => 0..2,
:message => "{{value}} must be 0, 1, or 2"
Rails 在这里查看:
<h1>Listing tasks</h1>
<table>
<tr>
<th>Status</th>
<th>Name</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @tasks.each do |task| %>
<tr>
<td><%= task.status %></td>
<td><%= task.name %></td>
<td><%= link_to 'Show', task %></td>
<td><%= link_to 'Edit', edit_task_path(task) %></td>
<td><%= link_to 'Delete', task, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
要求
将任务的状态存储在数据库中,使值易于本地化,即我不确定是否要将“正常”、“事件”、“已完成”存储为字符串字段。
解决方案必须适用于 Rails 3.0。
问题:
我应该将字段存储为整数(见上文)吗?如果是这样,我如何在我的 Rails View 中的 HTML 表中显示正确的人类可读状态,例如在 HTML 表格中显示“Active”而不是“1”。
我应该使用枚举吗?如果可以,以后本地化容易吗?
我应该使用直字符串吗? “正常”、“事件”、“完成”
您能否提供 View 帮助程序、 Controller 或 View 代码的快速代码示例以实现此目的?
最佳答案
1.这取决于您希望优化数据库查询的程度。
2. 不是真的, AR 不支持“开箱即用”。 # 从 Rails 4 开始 enums are supported out of the box .
3.恕我直言,您可以使用字符串而不会造成很大的性能损失(只需记住将字段添加到索引中)。我会这样做,因为它更容易国际化和维护。但是,如果您需要额外的性能,您可以使用整数。
您可以查看 2 个 SO 线程 here和 here这是有争议的。
4.如果你想将它们保持为整数,你可以通过以下方式实现:
class Task << AR::Base
NORMAL = 1
ACTIVE = 2
COMPLETED = 3
STATUSES = {
NORMAL => 'normal',
ACTIVE => 'active',
COMPLETED => 'completed'
}
validates_inclusion_of :status, :in => STATUSES.keys,
:message => "{{value}} must be in #{STATUSES.values.join ','}"
# just a helper method for the view
def status_name
STATUSES[status]
end
end
在 View 中:
<td><%= task.status_name %></td>
如果要使用字符串,就更简单了:
STATUSES = ['normal', 'active', 'completed']
validates_inclusion_of :status, :in => STATUSES,
:message => "{{value}} must be in #{STATUSES.join ','}"
关于html - 在 Rails 中,我应该如何为任务应用程序实现状态字段 - 整数或枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2650897/