【问题标题】:Form_For undefined method pathForm_For 未定义的方法路径
【发布时间】:2025-12-31 08:55:10
【问题描述】:

我正在尝试嵌套资源:

我的路线:

  resources :conversations do
    resources :replies do
      resources :comments
    end
  end

我能够获得回复表单以处理对话,但现在我增加了让 cmets 处理回复的额外复杂性。

整个表格都在对话显示路径下。

<%= form_for([@conversation, @reply]) do |f| %>
    <%= render 'shared/response_form', f: f %>
    <%= f.submit "Reply", class: "btn btn-large btn-primary" %>
<% end %>

上面的回复表格可以正常工作,没有错误,下面的 cmets 表格有错误:

未定义的方法`reply_cmets_path'

<%= form_for([@reply, @comment]) do |f| %>
    <%= render 'shared/response_form', f: f %>
    <%= f.submit "Comment", class: "btn btn-large btn-primary" %>
<% end %>

这是我的节目对话控制器,这是我认为问题所在:

  def show
    @conversation = Conversation.find(params[:id])
    @replies = @conversation.replies
    @reply = current_user.replies.build
    #If I change the above line to @conversations.replies.build 
    #it breaks the ability to show replies above the form.

    @comments = @reply.comments
    @comment = @reply.comments.build    
  end

但是,其他人建议这样做:

<%= form_for([@conversation, @reply, @comment]) do |f| %>
    <%= render 'shared/response_form', f: f %>
    <%= f.submit "Comment", class: "btn btn-large btn-primary" %>
<% end %>

但它只是以路由错误结束:

No route matches {:controller=>"comments", :format=>nil, :conversation_id=>#<Conversation id: 3, content: "Goes here.", user_id: 1, created_at: "2012-12-10 21:20:01", updated_at: "2012-12-10 21:20:01", subject: "Another conversation">, :reply_id=>#<Reply id: nil, content: nil, user_id: 1, created_at: nil, updated_at: nil, conversation_id: nil>}

当我尝试制作新表单时,我总是遇到这个未定义的方法路径错误,而且我总是设法忘记我做错了什么。答案似乎从来都不是路线。

编辑:

在我拥有的控制器的创建部分下:

@replies = @conversation.replies
@reply = current_user.replies.build
#If I change the above line to @conversations.replies.build 
#it breaks the ability to show replies above the form.

我不知道为什么 @reply = @conversation.replies.build 会破坏显示现有回复的能力。我收到一条错误消息,说它无法将 nil 转换为数字,并且看不到 reply.created_at 或 reply.content。无论是什么原因,这都可能是我为什么会遇到这个问题的线索。但是,在回复控制器中,我正在使用

@reply = conversation.replies.build(content: params[:reply][:content], user_id: current_user.id)

编辑:

补充一点,* 所做的事情与我在这里尝试实现的非常相似,只是您可以对问题和答案发表评论。

【问题讨论】:

    标签: ruby-on-rails nested-routes nested-form-for


    【解决方案1】:

    查看错误的结尾:

    ... :reply_id=>#<Reply id: nil, content: nil, user_id: 1, created_at: nil, updated_at: nil, conversation_id: nil>}
    

    如果@reply 未保存,您将无法为@comment 创建表单。您需要先持久化@reply,然后再为其创建@comment

    如果您尚未验证回复模型,请尝试对显示操作进行此简单测试:

    # @reply = current_user.replies.build
    @reply = current_user.replies.create
    

    请参阅 cmets 以获得答案。

    【讨论】:

    • 事情是表单只显示 ,所以它甚至不应该出现在没有回复的对话中。
    • 我测试了这个,如果没有回复,它肯定不会显示表单或出现任何错误。
    • 我重新阅读了您的问题,但我很怀疑,您想要在没有对话的情况下创建回复/评论?如果不是,你为什么使用current_user.replies.build
    • 就是这样,如果您看到我在该行下方制作的 cmets,我不知道为什么会这样。在创建下的回复控制器中,我有@conversation.replies.build(等。我不知道为什么它不会让我在不破坏显示现有回复的能力的情况下做你所说的事情。可能是什么原因造成的为什么这不起作用的关键。
    • 您对回复模型有任何验证吗?