Rails has_many :through saving additional fields

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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>

回答1:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!