Nested attributes for belongs_to association rails
Asked Answered
U

1

14

I have two models, Complaint and Company. Complaint belongs_to and accepts_nested_attributes for Company, and Company has_many Complaints.

# Models

class Complaint < ActiveRecord::Base
  attr_accessible :complaint, :date, :resolved

  belongs_to :user, :class_name => 'User', :foreign_key => 'id'
  belongs_to :company, :class_name => 'Company', :foreign_key => 'id'
  has_many :replies

  accepts_nested_attributes_for :company

end

class Company < ActiveRecord::Base
  attr_accessible :name

  has_many :complaints, :class_name => 'Complaint', :foreign_key => 'id'
  has_many :branches, :class_name => 'Branch', :foreign_key => 'id'
  belongs_to :industry

end

In the Complaint Controller I try build a Company in the new method.

# Complaint Controller

class ComplaintsController < ApplicationController
...
def new
    @complaint = Complaint.new
    @complaint.build_company

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @complaint }
    end
  end
...
end

In the form I have added a field for adding a name attribute to the Company.

# Complaint Form

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

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

  <div class="field">
    <%= f.label :complaint %><br />
    <%= f.text_area :complaint, :rows => 5 %>
  </div>
  <div class="field">
    <%= f.label :date %><br />
    <%= f.datetime_select :date %>
  </div>

  <% if current_user.try(:admin?) %>
    <div class="field">
      <%= f.label :resolved %><br />
      <%= f.check_box :resolved %>
    </div>
  <% end %>

  <%= fields_for :company do |company| %>
    <div class="field">
      <%= company.label :name, 'Company' %>
      <%= company.text_field :name %>
    </div>
  <% end %>

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

The form submits but only the Complaint is saved. The user input for Company is disregarded. Why won't this create a new Company?

Unbounded answered 18/3, 2013 at 6:46 Comment(3)
Hi @pjmil, i am facing the same problem.will you please tell me strong parameter oF Complaint Controller?Gallegos
Hi, I am facing same problem. How did you fix it.Carreon
@Unbounded Thank you very much for the post. But could you please share your strong parameters for the same. Also, if possible, can you please share the parameters that you get on submitting the form? ThanksDiatonic
U
19

My mistake was in the form. I missed the f. before the fields_for :company

<%= f.fields_for :company do |company| %>
Unbounded answered 17/10, 2013 at 2:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.