Ruby on Rails, form_for with 3 levels

1

I'm trying to create comment, through form_for of 3 levels:
Article > Item > Comment

Controller:
 def new
  @comment = Comment.new
 end

I have already tried it in several ways, and all of them give error. Look at what I tried and the error that returned:

1st try:

<%= form_for([@item, @item.comments.build]) do |f| %>

  

Error: undefined method 'item_comments_path' for

2nd attempt:

<%= form_for ([@item, @comment]) do |f| %>

  

Error: First argument in form can not contain nil or be empty

3rd Try:

<%= form_for @category do |f| %>  
        <%= f.fields_for @item do |i| %>  
            <%= i.fields_for @comments do |c| %>
  

Error: undefined method 'model_name' for nil: NilClass

I do not know what to try, how could I solve this?

    
asked by anonymous 06.11.2016 / 16:35

1 answer

1

Article.rb

  has_many  :items #repare no plural
  accepts_nested_attributes_for :items

Item.rb

  belongs_to :article, required: false  #repare no singular
  has_many  :comments
  accepts_nested_attributes_for :comments

Comment.rb

  belongs_to :item, required: false

In the controller of the parent classes have to have in def new @ pai.filhos.build example (I am considering which article is the parent of item that is comment parent:

articles_controller.rb

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

Use your third form.

<%= form_for @category do |f| %>  
        <%= f.fields_for @item do |i| %>  
            <%= i.fields_for @comments do |c| %>

Generally type errors:        Error: undefined method 'model_name' for nil: NilClass are correcting themselves by initializing the model-name in the action of the controller that you are accessing:

def action
  @model-name = Model-name.new
end 

or

def action
   @model-name-pai = Model-name-pai.new
   @model-name-pai.model-names.build  #(repare no plural do filho: model-nameS)
end
    
08.11.2016 / 18:13