多对多:has_many:通过关联表单以及分配给链接模型的数据来创建表单视图 [英] many-to-many: has_many :through association form with data assigned to linking model create form view
问题描述
我正在玩Rails指南中的示例:
I'm playing with an example from Rails Guides:
http://guides.rubyonrails.org/association_basics.html# the-has_many-through-association
此示例对模型具有以下设置:
This example has the following setup for the models:
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 Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end
我正试图了解如何做以下两件事:
I'm trying to understand how to do the following two things:
- 如何设置将创建新患者并使用现有医生指定约会时间的视图
- 如何为现有患者分配新医师和预约时间的预约
我经历了RailsCasts 196& 197处理嵌套表单,但我不知道它如何适用于这种情况.
I went through the RailsCasts 196 & 197 that deal with nested forms, but I don't see how it would apply to this situation.
请问有人可以提供示例或指向我吗?
Can someone provide an example or point me to a guide on this please?
谢谢
推荐答案
首先,您必须将医师ID传递给您的PatientsController#new
操作.如果用户通过跟踪链接到达那里,那将是
First you have to pass the physician ID to your PatientsController#new
action. If users get there by folloing a link, this would be something like
<%= link_to 'Create an appointment', new_patient_path(:physician_id => @physician.id) %>
或者,如果用户必须提交表单,则可以使用它提交一个隐藏字段:
Or, if users have to submit a form, you can submit a hidden field with it:
<%= f.hidden_field :physician_id, @physician.id %>
然后,在PatientsController#new
中:
def new
@patient = Patient.new
@physician = Physician.find(params[:physician_id])
@patient.appointments.build(:physician_id => @physician.id)
end
在new.html.erb
中:
<%= form_for @patient do |f| %>
...
<%= f.fields_for :appointments do |ff |%>
<%= ff.hidden_field :physician_id %>
...
<% end %>
<% end %>
这篇关于多对多:has_many:通过关联表单以及分配给链接模型的数据来创建表单视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!