Rails has_many:通过保存其他字段

时间:2013-01-09 16:55:01

标签: ruby-on-rails ruby

我正在尝试找到一种优雅的方法来在约会模型上保存一个名为描述的附加字段(如下所示)。我的模型设置如下:

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>

1 个答案:

答案 0 :(得分: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