lscott3
lscott3

Reputation: 106

Rails has_many :through saving additional fields

I am trying to find a graceful way of saving an additional field called description on the Appointment model (below). My models are setup like this:

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

In my view I have checkboxes setup to save the data for the join table but I want to slide in an additional "description" field to be saved with the join. Below is what is in my view:

<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>

Upvotes: 5

Views: 1745

Answers (1)

siddick
siddick

Reputation: 1478

You can use accepts_nested_attributes_for to update the association attributes.

In Model:

accepts_nested_attributes_for :appointments, :allow_destroy => true

In View:

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

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

Upvotes: 2

Related Questions