Undefined method build in rails 4 has_many association

Zakoff picture Zakoff · Nov 1, 2014 · Viewed 8.2k times · Source

I have the following set up in rails:

Document has_many Sections
Section belongs_to Document

The Section form is completed in the documents/show view...the Document controller for this action is:

  def show
    @document = current_user.documents.find(params[:id])
    @section = Section.new if logged_in?
  end

The Section form in documents/show is as follows:

<%= form_for(@section) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
      <%= f.text_area :content, placeholder: "Compose new section..." %>
  </div>
  <%= hidden_field_tag :document_id, @document.id %> 
  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

Where you can see a hidden_field_tag is sending the document_id

The sections_controller is as follows:

class SectionsController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy, :show, :index]

  def create
    @document = Document.find(params[:document_id])
    @section = @document.build(section_params)
    if @section.save
      flash[:success] = "Section created!"
      redirect_to user_path(current_user)
    else
      render 'static_pages/home'
    end
  end

  def destroy
  end

  def index
  end

  private

    def section_params
      params.require(:section).permit(:content)
    end
end

I get the following error which I have not been able to resolve.

**NoMethodError (undefined method `build' for #<Document:0x00000004e48640>):
  app/controllers/sections_controller.rb:6:in `create'**

I am sure it must be something simple I am overlooking but can't seem to find it. Any help would be appreciated:

Answer

Arup Rakshit picture Arup Rakshit · Nov 1, 2014

Replace the below line :-

@section = @document.build(section_params)

with

@section = @document.sections.build(section_params)

You have a has_many associations named sections in the Document model. Thus as per the guide, you got the method collection.build(attributes = {}, ...). Read the section 4.3.1.14 collection.build(attributes = {}, ...) under the link I gave to you.