Rails fields_for表单未显示,嵌套表单

时间:2013-06-18 18:05:59

标签: ruby-on-rails ruby ruby-on-rails-3

我创建了一个简单的rails项目。一切正常,直到我尝试添加新Paintings belongs_to治疗和Patient has_many通过治疗的绘画。所以我创建的嵌套表单不会显示出来,我相信它与控制器有关!谢谢,来自德国的问候!

治疗控制器:

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进行治疗的表格没有显示:

<%= form_for([@patient, @patient.treatments.build]) do |f| %>
  <div class="field">
    <%= f.label :content %>
    <%= f.text_area :content, :cols => "30", :rows => "10" %>
  </div>
  <div class="field">
    <%= f.label :category_id %>
    <%= f.collection_select :category_id, Category.find(:all), :id, :typ %>
  </div>

  <%= f.fields_for :paintings do |ff| %>
    <div class="field">
      <%= ff.label :name, 'Tag:' %>
      <%= ff.text_field :name %>
    </div>
  <% end %>

  <div class="field">
    <%= f.submit nil, :class => 'btn btn-small btn-primary' %>
  </div>
<% end %>

更新

显示网站:

<% @patient.treatments.each do |treatment| %>
  <tr>
    <td><%= treatment.category.try(:typ) %></td>
    <td><%= treatment.content %></td>
    <td><%= treatment.day %></td>
    <td><div class="arrow"></div></td>
  </tr>
  <tr>

4 个答案:

答案 0 :(得分:59)

请尝试

= f.fields_for :paintings, Painting.new do |p|

答案 1 :(得分:12)

即使问题已经很久了,但你错过了对这个问题至关重要的new。方法destroycreate对此问题没有任何帮助。如果你有一个new方法,它看起来像这样:

class TreatmentsController < ApplicationController
  def new
    @patient = Patient.new
  end
end

然后解决方案是将new方法修改为&#34; build&#34; paintings就像这样:

class TreatmentsController < ApplicationController
  def new
    @patient = Patient.new
    @patient.paintings.build
  end
end

答案 2 :(得分:9)

尝试在控制器

中的新操作中执行以下操作
@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

答案 3 :(得分:2)

对谁有用,我正在使用:

<% f.fields_for :partner do |fp| %>

代替:

<%= f.fields_for :partner do |fp| %>