Rails fields_for表单未显示,嵌套表单
我创建了一个简单的rails项目。 一切正常,直到我试图添加一个belongs_to
治疗的新模型Paintings
和一个通过治疗有很多绘画的Patient
。 所以我创建的嵌套表单不会显示出来,我相信它与控制器有关! 谢谢,德国的问候!
治疗控制器:
class TreatmentsController < ApplicationController def create @patient = Patient.find(params[:patient_id]) @treatment = @patient.treatments.create(params[:treatment]) redirect_to patient_path(@patient) end def destroy @patient = Patient.find(params[:patient_id]) @treatment = @patient.treatments.find(params[:id]) @treatment.destroy redirect_to patient_path(@patient) end end
并且没有显示nested fields_for
处理表单:
"30", :rows => "10" %> 'btn btn-small btn-primary' %>
更新:
显示网站:
请试试
= f.fields_for :paintings, Painting.new do |p|
即使这个问题已经很老了,但你错过了对这个问题至关重要的new
问题。 destroy
和create
方法没有任何问题。 如果您有一个new
方法,看起来像这样:
class TreatmentsController < ApplicationController def new @patient = Patient.new end end
然后解决方案是修改new
方法来“构建”这样的paintings
:
class TreatmentsController < ApplicationController def new @patient = Patient.new @patient.paintings.build end end
尝试在控制器中执行以下操作
@patient.treatments.build
查看build_association部分http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to
您还应该阅读有关嵌套属性的信息。 使用这些参考http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html