【问题标题】:Rails 3 Attendance Form with Multiple days per week and Multiple childrenRails 3 出勤表,每周多天和多个孩子
【发布时间】:2013-05-16 12:56:44
【问题描述】:

我正在尝试创建一个表单,让您可以输入或更新每天的出勤时间,并能够显示每个孩子每周的记录。 我在试图弄清楚如何用这样的表格实现表格时遇到了麻烦:

            <- Previous Week                                         Next Week -> 
| Child   | Monday 5/6 | Tuesday 5/7 | Wednesday 5/8 | Thursday 5/9 | Friday 5/10 |
| child1  | __________ | ___________ | _____________ | ____________ | ___________ |
| child2  | __________ | ___________ | _____________ | ____________ | ___________ |
Submit

我目前有两个具有 has_one 和 has_many 关系的模型:

class Child < ActiveRecord::Base
  validates :first, presence: true
  validates :last, presence: true
  attr_accessible :age, :first, :last, :created_at
  belongs_to :site
  has_many :attendances
end

class Attendance < ActiveRecord::Base
  attr_accessible :date, :time, :child_id
  belongs_to :child

  scope :thisweek, lambda {
    where("date between ? and ?", Date.today.at_beginning_of_week, Date.today.at_end_of_week)
  }
end

我还有 2 个用于儿童和出勤的脚手架控制器,我能够通过如下查询加载一周所需的所有数据:

class AttendancesController < ApplicationController
  def index
    @site = Site.find(params[:site_id]) #using nested resources /site/1/attendances
    @children = @site.children.all
    @attendances = Attendance.thisweek.find_all_by_child_id(@children)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @attendances }
    end
  end
 end

除此之外,我还纠结于如何将这些数据转换为上述表格。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-3.2


    【解决方案1】:

    您正在寻找的是李克特。我正在为同样的需求构建一个表单助手 gem,但是还没有完成。

    这样的事情会让你开始:

    <%= form_tag(:attendance) do %>
      <table>
        <thead>
          <tr>
            <th> Child </th>
            <% @dates.each do |date| %>
            <th><%= date.day %></th>
            <% end %>
          </tr>
        </thead>
        <tbody>
          <% @children.each do |child| %>
          <tr>
            <td><%= child.name %></td>
            <%= child.attendances.thisweek.each do |attendance| %>
            <td><%= check_box_tag "children[#{child.id}][attendance][attendance.id][present]", child.attendances.present %></td>
            <% end %>
          </tr>
          <% end %>
        </tbody>
      </table>
    <% end %>
    

    @dates = 无论您打算如何获取它,可能与@attendances 不同。

    我假设您需要的只是一个布尔值,存在或不存在,所以我使用了 check_box_tag,但您可以随意调整它以适应您的应用程序。这只是一个例子。这也假设该周的出勤率已经存在并且与孩子相关联。

    如上所述,这是一个开始,您可以了解如何根据自己的需要调整它。

    【讨论】:

      猜你喜欢
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多