我正在玩Rails指南中的一个例子:
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
此示例对模型进行了以下设置:
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
我正在努力了解如何做以下两件事:
我浏览了RailsCasts 196&amp; 197处理嵌套表格,但我不知道它将如何适用于这种情况。
有人可以提供一个例子或指向我这方面的指南吗?
谢谢
答案 0 :(得分:3)
首先,您必须将医生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 %>