Home>

I'm trying to select a category, create content, and leave a comment on that content.

The routing is as follows.

resources: categories, only: [: index,: new,: create] do
    resources: contents do
      resources: comments
    end
  end


Up to the content could be saved with the following description

def create
    @category = Category.find (params [: category_id])
    @content = @ category.contents.new (content_params)
    @ content.save
  end
  private
  def content_params
    params.require (: content) .permit (: content,: category_id) .merge (user_id: current_user.id)
  end
What I tried

Comment input form


<% = form_with model: [@category, @content, @comment], class: "form", local: true do | f |%>
  <form>
      
      <% = f.text_field: comment, placeholder:'type a comment', class:'input-comment'%>
      
    <% = f.submit'SEND', class:'send-btn'%>
  </form>
<% end%>


Comment controller

def create
    @category = Category.find (params [: category_id])
    @content = Content.find (params [: content_id])
    @comment = @ content.comments.new (comment_params)
    @ comment.save
  end
  private
  def comment_params
    params.require (: comment) .permit (: comment,: content_id) .merge (user_id: current_user.id)
  end

Parameters that came to the comment create method

Parameters: {"authenticity_token" =>"d1cssjlsFeCpwmnmzQeDkI3x49j/liIviVIVjeSr2LU8CtCXPz/mfZeFs5skbW8w + gDlYseQ/sV7Il8Ta7oTyg ==", "comment" == "," comment "=" category_id "=>" 1 "," content_id "=>" 1 "}
Error message
NoMethodError in CommentsController # create
undefined method `comments' for #<Content:


There seems to be a problem with @ comment = @ content.comments.new (comment_params) in the above method.
I tried various descriptions, but it doesn't work.

I am creating an application from scratch for the first time.
I think there are many unsightly parts, but please give me guidance.

Postscript -----

Association

devise: database_authenticatable,: registerable,
         : recoverable,: rememberable,: validatable
  has_many: contents, through:: comments
  has_many: categories, through:: contents
  has_many: comments
belongs_to: user
  has_many: contents
  has_many: users, through:: contents
belongs_to: user
  belongs_to: category
  has_many: user, through:: comments
belongs_to: user
  belongs_to: content


Has become

  • Answer # 1

    Resolved by changing the association

    devise: database_authenticatable,: registerable,
             : recoverable,: rememberable,: validatable
      has_many: contents
      has_many: categories
      has_many: categories, through:: contents
      has_many: comments
    belongs_to: user
      belongs_to: category
      has_many: comments
      has_many: user, through:: comments