Search code examples
ruby-on-railsrubyroutesnested-resources

simple_form undefined method model_name 3 classes error


So I just Nested some resources that weren't Nested before and since I have been trying to fix all of the path references. The biggest issue I have been having is with the fact that there are 2 nested resources within a larger nested resource like so:

Users->Photos->Comments

On my form, it keeps giving me the following error

undefined method `model_name' for "/users/2/photos/2/comments/new":String

The error page says that the source is around line #1 of the following (my comments/_form partial):

= simple_form_for ([@comment, new_user_photo_comment_path(@user,@photos,@comment)]) do |f|
  = f.input :content, label: "Reply to thread"
  =f.button :submit, class: "button"

This is my Comments controller:

class CommentsController < ApplicationController
  before_action :authenticate_user!
  def new
    @photo=Photo.find(params[:photo_id])
  end
  def create
    @photo =Photo.find(params[:photo_id])
    @comment=Comment.create(params[:comment].permit(:content, :id, :photo_id))
    @comment.user_id= current_user.id
    @comment.photo_id= @photo.id
    @user= User.find_by(params[:id])

    if @comment.save
      redirect_to user_photo_path(@photo, @user)
    else
      render 'comments/new'
    end
  end
end

Solution

  • At first, it is not preferably to nest resources deeper than two times. You should consider to nest comments within only photos. It`s ok to do like so in routes.rb:

    resources :users do
      resources :photos
    end
    
    resources :photos do
      resources :comments
    end
    

    And you errors is because = simple_form_for ([@comment, new_user_photo_comment_path(@user,@photos,@comment)]) do |f| gives for method simple_form_for as parameters:
    1 - model Comment
    2 - String /users/2/photos/2/comments/new

    to set proper path (form action) form builders need models as all arguments. Maybe something like = simple_form_for ([@user,@photos,@comment]) do |f| should work