gpt4 book ai didi

ruby-on-rails - Rails has_many :through saving additional fields

转载 作者:数据小太阳 更新时间:2023-10-29 07:18:35 25 4
gpt4 key购买 nike

我正在尝试找到一种优雅的方式来保存约会模型(如下)中称为描述的附加字段。我的模型是这样设置的:

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>

最佳答案

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

在模型中:

accepts_nested_attributes_for :appointments, :allow_destroy => true

在 View 中:

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

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

关于ruby-on-rails - Rails has_many :through saving additional fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com