Rails has_many :通过保存额外的字段 [英] Rails has_many :through saving additional fields
问题描述
我正在尝试找到一种优雅的方式来保存约会模型中名为 description 的附加字段(如下所示).我的模型设置如下:
class Physician <ActiveRecord::Basehas_many : 约会has_many :患者, 通过: :appointments结尾班级预约
在我看来,我设置了复选框来保存联接表的数据,但我想在附加的描述"字段中滑动以与联接一起保存.以下是我的看法:
<字段集><legend>患者</legend><% @patients.each_slice(2) 做 |切片|%><% slice.each do |患者|%><%= label_tag "physician_patient_ids_#{patient.id}" do %><%= check_box_tag '医师[patient_ids][]',patient.id,@physician.patients.include?(患者),{ id: "physician_patient_ids_#{patient.id}" } %><%=患者姓名%><%结束%><!-- 需要以某种方式在此处添加说明--><%结束%>
<%结束%></fieldset>
您可以使用 accepts_nested_attributes_for
来更新关联属性.
在模型中:
accepts_nested_attributes_for :appointments, :allow_destroy =>真的
在视图中:
<%= f.fields_for :appointments do |apt|%><%= apt.object.patient.name %><%= apt.text_field :description %><%结束%>
参考 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
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>
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
这篇关于Rails has_many :通过保存额外的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!