【问题标题】:Rails has_many :through saving additional fieldsRails has_many :通过保存附加字段
【发布时间】:2013-01-09 16:55:01
【问题描述】:

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

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>

【问题讨论】:

  • Patients 模型不会错过 has_many 关联吗?
  • 是的,这对我来说是一团糟。关系就在那里,我将对其进行编辑以反映这一点。

标签: ruby-on-rails ruby


【解决方案1】:

您可以使用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

【讨论】:

  • 别忘了你还需要在你的控制器中为 strong_params 添加必要的参数
猜你喜欢
  • 2015-12-02
  • 2017-11-27
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 2011-07-18
相关资源
最近更新 更多