Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails fields_for form not showing up, nested form

I have created an simple rails project. All worked fine until I tried to add a new model Paintings that belongs_to treatment and an Patient that has_many Paintings through Treatment. So somehow the nested form I created does not show up, I believe it has to do with the controller! Thanks, and greetings from Germany!

Treatments controller:

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

And the form for treatments with nested fields_for that doesn't show up:

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

UPDATE:

Show Site:

<% @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>
like image 254
Em Sta Avatar asked Jun 18 '13 18:06

Em Sta


2 Answers

Please try

= f.fields_for :paintings, Painting.new do |p|
like image 192
prasad.surase Avatar answered Nov 06 '22 21:11

prasad.surase


Even the question is quite old, but you are missing the new that is crucial to this question. The methods destroy and create doesn't have anything with this issue. If you have a new method, which looks something like this:

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

Then the solution would be do modify the new method to "build" the paintings like this:

class TreatmentsController < ApplicationController
  def new
    @patient = Patient.new
    @patient.paintings.build
  end
end
like image 16
Aleks Avatar answered Nov 06 '22 20:11

Aleks