2

I'm having trouble understanding nested resources. There is a Service scaffold, and there is Symptom model. I wanted to be able to add the symptom_item string to the service scaffold.

This is my current show template code:

<% if @service.symptoms.any? %>
  <% @service.symptoms.each do |symptom| %>
    <li><%= symptom.symptom_item %></li>
  <% end %>
<% else %>
  <p>
    none
  </p>
<% end %>

Here is my form code:

<%= form_for(@service) do |f| %>
  <% if @service.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@service.errors.count, "error") %> prohibited this service from being saved:</h2>

      <ul>
      <% @service.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :s_text %><br>
    <%= f.text_area :s_text %>
  </div>
  <div class="field">
    <%= f.label :img_text %><br>
    <%= f.text_field :img_text %>
  </div>

<%= f.fields_for :symptoms do |builder| %>
  <div class="field">
    <%= builder.label :symptom_item %><br>
    <%= builder.text_field :symptom_item, :rows => 3 %>
  </div>
<% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Here is my controller code that allow the symptom_attributes:

def service_params
  params.require(:service).permit(:name, :s_text, :img_text, symptom_attributes: [:id, :service_item])
end

I know the problem is in the show template. When I write something as simple as:

= @service.symptoms

it gives me something funky like this:

#<Symptom::ActiveRecord_Associations_CollectionProxy:0x000000095295c8>

Does anyone see what's wrong with my code in the show template or maybe some where else?

Here are my models just in case:

class Service < ActiveRecord::Base
  has_many :symptoms
  accepts_nested_attributes_for :symptoms, allow_destroy: true
end

class Symptom < ActiveRecord::Base
  belongs_to :service
end
tereško
  • 58,060
  • 25
  • 98
  • 150
pk36
  • 33
  • 5

1 Answers1

0

It should be symptoms_attributes instead of symptom_attributes and symptom_item instead of service_item in your strong parameters

def service_params
  params.require(:service).permit(:name, :s_text, :img_text, symptoms_attributes: [:id, :symptom_item])
end
Ren
  • 1,379
  • 2
  • 12
  • 24