Rails中多表单复选框的数据库结构 [英] Database Structure for Multiple Form Checkboxes in Rails
问题描述
我有一个rails应用程序,我正在工作,允许用户创建一个时间表。在这样做时,他们应该能够选择一个星期中的事件发生。我计划在一个窗体中这样做的方式是每个工作日旁边的复选框,如下:
I have a rails app I am working on that allows users to create a schedule. In doing so, they should be able to select on which days of the week an event occurs. The way I was planning on doing this in a form was a checkbox next to every, weekday, like so:
<%= f.check_box :monday %> <%= f.label :monday %>
<%= f.check_box :tuesday %> <%= f.label :tuesday %>
<%= f.check_box :wednesday %> <%= f.label :wednesday %>
等...
它发生对我,这可能不是一个非常有效的方式处理这个,存储每个日期作为一个布尔值在数据库中。在显示视图中显示日期将非常困难;我必须做类似
However, It occured to me that this probably isn't a very efficient way of handling this, storing each date as a boolean value in the database. It will be very difficult to display the dates in the 'show' view; I'll have to do something like
Event Dates:
<% if @event.monday? %>
Monday
<% end %>
<% if @event.tuesday? %>
Tuesday
<% end %>
<% if @event.wednesday? %>
Wednesday
<% end %>
这对我来说似乎不太理想。
Which seems less than ideal to me.
我的另一个想法是在数据库中创建一个字符串列,其中包含所有的事件日期,使用attr_accesors和一个模型方法创建字符串after_create。但是,在这种情况下,用户如何能够编辑事件?
My other idea would be to just create one string column in the database that holds all of the event dates, using attr_accesors and a model method to create the string after_create. However, in this case, how will users be able to edit the Event?
它让我想到,在这里必须有一些最佳做法,我不知道(我从来没有尝试过创建这种类型的结构之前)。
It got me thinking, there must be some sort of best practice here that I don't know about (I've never tried to create something with this type of structure before).
任何意见?
谢谢!
推荐答案
不要这样做:
我的其他想法是创建一个字符串列保存所有事件日期的数据库,使用attr_accesors和一个模型方法创建字符串after_create。
My other idea would be to just create one string column in the database that holds all of the event dates, using attr_accesors and a model method to create the string after_create.
只是导致问题,如使每日查询一个可怕的丑陋的混乱;例如,如果您将星期几存储在一个列中,您将如何计算星期一有多少活动?
That sort of thing will just cause problems like making per-day queries a horrific ugly mess; how would you, for example, count how many events are available on Monday if you stored your days mashed into a single column?
而是保留您的七个布尔值并添加简单的方便方法到您的模型,返回一些更方便的格式的日子。这样的事情可能:
Instead, keep your seven booleans and add a simple convenience method to your model that returns the days in some more convenient format. Something like this perhaps:
def days
Date.DAYNAMES.map { |d| read_attribute(d.downcase) }
end
,然后可以简单地遍历 @ event.days
并将日期数字映射到名称:
and then you can simply iterate over @event.days
in your view and map the day numbers to names:
<% @event.days.each_with_index do |on_day, i| %>
<% if on_day %>
<%= Date.DAYNAMES[i] %>
<% end %>
<% end %>
天
方法的具体细节如何在你的雇员再培训局处理它,当然会取决于你的具体情况。
The specific details of the days
method and how you deal with it in your ERB will, of course, depend on your specific circumstances.
这篇关于Rails中多表单复选框的数据库结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!