many-to-many:has_many:通过关联表单与分配给链接模型的数据创建表单视图

我正在玩Rails指南中的一个例子:

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

此示例具有以下模型设置:

class Physician  :appointments end class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient end class Patient  :appointments end 

我试图了解如何做以下两件事:

  1. 如何设置创建新患者的视图,并为具有指定时间的现有医生分配约会
  2. 如何为现有患者分配新医师和预约时间

我经历了处理嵌套表单的RailsCasts 196和197,但我不知道它将如何应用于这种情况。

有人可以提供一个例子或指向我这方面的指南吗?

谢谢

首先,您必须将医生ID传递给您的PatientsController#new动作。 如果用户通过链接到达那里,这将是类似的

 <%= link_to 'Create an appointment', new_patient_path(:physician_id => @physician.id) %> 

或者,如果用户必须提交表单,您可以使用它提交隐藏字段:

 <%= 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 %>