用rails包裹并创建div

时间:2013-08-27 12:37:31

标签: ruby-on-rails ruby-on-rails-3

我有div Tasks。每个Task都是单独的form

<div id="tasks">
    <form id="task">...(@task.date = 2013-08-25)...</form>
    <form id="task">...(@task.date = 2013-08-25)...</form>
    <form id="task">...(@task.date = 2013-08-24)...</form>
    <form id="task">...(@task.date = 2013-08-23)...</form>
    <form id="task">...(@task.date = 2013-08-23)...</form>
    <form id="task">...(@task.date = 2013-08-23)...</form>
    <form id="task">...(@task.date = 2013-08-21)...</form>
    <form id="task">...(@task.date = 2013-08-21)...</form>
</div>

我想将Tasksdate分开div分开,并添加div标题信息。

<div id="tasks">
    <div class="day_tasks">
        <div class="day_tasks_header">...</div>
        <form id="task">...(@task.date = 2013-08-25)...</form>
        <form id="task">...(@task.date = 2013-08-25)...</form>
    </div>
    <div class="day_tasks">
        <div class="day_tasks_header">...</div>
        <form id="task">...(@task.date = 2013-08-24)...</form>
    </div>
    <div class="day_tasks">
        <div class="day_tasks_header">...</div>
        <form id="task">...(@task.date = 2013-08-23)...</form>
        <form id="task">...(@task.date = 2013-08-23)...</form>
        <form id="task">...(@task.date = 2013-08-23)...</form>
    </div>
    <div class="day_tasks">
        <div class="day_tasks_header">...</div>
        <form id="task">...(@task.date = 2013-08-21)...</form>
        <form id="task">...(@task.date = 2013-08-21)...</form>
    </div>
</div>

可以在div的类名和date div中添加.wrapAll,使用jQuery在单独的div中添加相同的类,然后.prepend()在顶部添加标题信息的div这个单独的div。但我不想把这么多的视图逻辑从rails端放到JS端。

是否可以使用Rails进行操作?

我的index.html.erb相当简单:

<%= content_tag(:div, id: 'tasks') do %>
    <%= render @tasks %>
<% end %>

_task.html.erb也是一个简单的<%= form_for task ... %>

1 个答案:

答案 0 :(得分:2)

ruby​​中有一个方法group_by,我认为这可以帮助您实现这一目标。您可以按日期对任务进行分组。你需要稍微改变你的渲染方法,但正如你所说,它比在javascript中做它更整洁。

因此,要对您的任务进行分组,您可以这样做:

grouped_tasks = @tasks.group_by(&:date)

这将返回一个哈希,将日期映射到具有该日期的任务,例如:

{ "2013-08-25" => [task1, task2],
  "2013-08-24" => [task3],
  "2013-08-23" => [task4, task5, task6],
  "2013-08-21" => [task7, task8] }

然后,您可以遍历分组以构建视图:

<div id="tasks">
  <% grouped_tasks.each do |date, tasks| %>
    <div class="day_tasks">
      <div class="day_tasks_header">...</div>
      <% tasks.each do |task| %>
        <%= form_for task ... %>
      <% end %>
    </div>
  <% end %>
</div>