Skip to content

Instantly share code, notes, and snippets.

@rummelonp
Created August 12, 2014 13:18
Show Gist options
  • Save rummelonp/682b3697bbb3b1c856cd to your computer and use it in GitHub Desktop.
Save rummelonp/682b3697bbb3b1c856cd to your computer and use it in GitHub Desktop.
A has_many B, B belongs_to C の A fields_for B で C を一覧に出しつつ checkbox で操作して作成したり削除したりしたいみたいなやつ
class Staff
  has_many :staff_holidays
  accepts_nested_attributes_for :staff_holidays, allow_destroy: true
end
class StaffHoliday
  has_many :staff_holidays
  belongs_to :holiday
end
class Holiday
end
<%= form_for @staff do |f| %>
  <table class="table table-striped table-bordered col-percent-60">
    <thead>
      <tr>
        <th><%= Holiday.human_attribute_name(:id) %></th>
        <th><%= Holiday.human_attribute_name(:name) %></th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <% Holiday.all.each do |holiday| %>
        <% staff_holiday = @staff.staff_holidays.to_a.find { |i| i.holiday_id == holiday.id } %>
        <% staff_holiday ||= @staff.holiday.new %>
        <%= f.fields_for :staff_holidays, staff_holiday do |f| %>
          <tr>
            <td><%= holiday.id %></td>
            <td><%= f.label :_destroy, holiday.name %></td>
            <td>
              <%= f.hidden_field :holiday_id, value: holiday.id %>
              <%= f.check_box :_destroy, {checked: !staff_holiday.new_record?}, false, true %>
            </td>
          </tr>
        <% end %>
      <% end %>
    </tbody>
  </table>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment