cocoon: Undefined method 'new_record' for nil:NilClass

Hello,

like a lot of people that posted issues in here, i read a lot about this issue and what could cause the error but im not able to see what is wrong, i even see my code as the one from the examples but it is clear it is not the same. Im getting this ‘undefined method new_record’ error, which i read is because is trying to delete something is not there, right? Okay, if i delete this remove_association, i get this error:

Association comments doesn’t exist on Comment

which is driving me crazy. Here is my code.

Comment model:

class Comment < ApplicationRecord belongs_to :article, inverse_of: :comments end

Article model

class Article < ApplicationRecord
  has_many :comments, dependent: :destroy, inverse_of: :article
  accepts_nested_attributes_for :comments, reject_if: :all_blank, allow_destroy: true
  validates :title, presence: true,
                    length: { minimum: 5 }

end

_comment_fields

<div class="nested-fields">
  <p>
    <strong>Commenter:</strong>
    <%= form.input :commenter %>
  </p>

  <p>
    <strong>Comment:</strong>
    <%= form.input :body %>
  </p>
  <p>
  </p>
</div>

show form

<%= simple_form_for([@article,@article.comments.build], local: true) do |form| %>
  <p>
    <%= form.label :commenter %><br>
    <%= form.text_field :commenter %>
  </p>
  <p>
    <%= form.label :body %><br>
    <%= form.text_area :body %>
  </p>
  <div id='comments'>
    <%= form.simple_fields_for :comments do |comment| %>
      <%= render 'comments/comment_fields', :form => comment %>
    <% end %>
    <div class='links'>
      <%= link_to_add_association 'add comentario', form, :comments %>
    </div>
  </div>
  <p>
    <%= form.submit %>
  </p>
<% end %>

Im not very sure about the part [@article,@article.comments.build] since im already doing that in the new method in the controller, but i think this is not giving the error.

And my ArticlesController

class ArticlesController < ApplicationController

  def index
    @articles = Article.all
  end

  def new
    @article = Article.new
    @article.comments.build
  end

  private
    def article_params
      params.require(:article).permit(:title, :text, comments_attributes: [:id, :commenter, :body, :_destroy])
    end
end

Sorry about asking about this error but i dont find the solution, and ive been reading the docs and issues of other people for a while. thank you in advance.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 16 (9 by maintainers)

Most upvoted comments

Okay, i finally did it, im able to add more nested comments although it doesnt make sense hahaha

Im closing this, thank you very much nathan!!