【发布时间】: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