5

我正在尝试找到一种优雅的方式来保存 Appointment 模型上的一个名为 description 的附加字段(如下)。我的模型设置如下:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patients < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
  attr_accessible :name
end

在我看来,我设置了复选框来保存连接表的数据,但我想滑入一个额外的“描述”字段以与连接一起保存。以下是我的看法:

<div class="field">
  <fieldset>
  <legend>Patients</legend>
  <% @patients.each_slice(2) do |slice| %>
    <div class='row'>
      <% slice.each do |patient| %>
        <div class='span3'>
          <%= label_tag "physician_patient_ids_#{patient.id}" do %>
            <%= check_box_tag 'physician[patient_ids][]', patient.id,
                              @physician.patients.include?(patient),
                              { id: "physician_patient_ids_#{patient.id}" } %>
            <%= patient.name %>
          <% end %>
          <!-- need to add in description here somehow -->
        </div>
      <% end %>
    </div>
  <% end %>
  </fieldset>
</div>
4

1 回答 1

2

您可以使用accepts_nested_attributes_for来更新关联属性。

在模型中:

accepts_nested_attributes_for :appointments, :allow_destroy => true

在视图中:

<%= f.fields_for :appointments do |apt| %>
  <%= apt.object.patient.name %>
  <%= apt.text_field :description %>
<% end %>

参考http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

于 2013-01-09T17:50:26.127 回答