Ruby on Rails, form_for with 3 levels

Asked

Viewed 103 times

1

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

Controller:
 def new
  @comment = Comment.new
 end

I have tried several ways, and they all fail. Look what I tried and the error that came back:

First attempt:

<%= 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 cannot contain nil or be Empty

Third attempt:

<%= 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 don’t know what else to try, how could I fix this?

  • I found the problem: I was inside the item show page, but rendering a partial add comment. I thought it would go through the Comment controller, but it was only going through the Item controller.

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 parent class controller you have to have in def new @pai.filhos.build example (I am considering that article is parent item that is parent of comment:

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 errors of the type: Error: Undefined method `model_name' for nil:Nilclass are correcting itself by initiating the model-name in the controller action 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
  • Paul! Super thank you for your contribution. My mistake was a little more silly. As I was creating a comment, I thought I should enter the new comment action, but since I was in show_item, and just add comment through a partial, I was forgetting to check in the Item controller. Of qqer way, I found it super interesting your approach. Now it’s working here, but I didn’t use "accepts_nested_attributes_for". I am doing wrong or there may be several correct ways in this case?

  • If yours is working then I think you’re right! rs I’m a beginner too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.