Rails 4路由助手生成意外路径

时间:2014-03-09 15:11:45

标签: ruby-on-rails ruby-on-rails-4 rails-routing

我有一个Rails 4应用程序,其中包含以下代码片段:

config/routes.rb

concern :messageable do
  resources :messages, only: [:create, :destroy]
end

namespace :recruiter do
  resources :applications, only: :show, concerns: :messageable
end

在特定视图中companies/application/_messages.html.erbCompaniesController application充当partials文件夹 - 此处使用的application变量是使用locals传递的)

<%= form_for [current_recruiter, application, Message.new], remote: true do |f| %>

产生

<form accept-charset="UTF-8" action="/recruiter/applications/4/messages" class="new_message" data-remote="true" id="new_message" method="post">

再次

<%= form_for recruiter_application_messages_path(application.id), remote: true do |f| %>

产生

<form accept-charset="UTF-8" action="/companies/2" data-remote="true" method="post">

为了记录,我觉得/recruiter/applications/4/messages中的“4”取自current_recruiter.id的值。我要找的是该占位符中application.id(在特定情况下为16)的值。有人可以帮我调试这个路线助手吗?

rake routes的相关输出:

recruiter_application_messages POST   /recruiter/applications/:application_id/messages(.:format)     recruiter/messages#create
recruiter_application_message DELETE /recruiter/applications/:application_id/messages/:id(.:format) recruiter/messages#destroy

1 个答案:

答案 0 :(得分:1)

我在考虑将此作为评论添加,但由于它有点长,我希望将此作为答案。

您的第一个form_for看起来像

form_for [current_recruiter, application, Message.new], remote: true do |f|

我假设current_recruiter是一个ActiveRecord对象,因此转换为recruiter_application_path与定义的路径冲突。我在现有项目中使用相同的代码进行了一些实验。在控制台中,我运行了以下

>> app.recruiter_application_messages_path(1)
=> "/recruiter/applications/1/messages"

>> app.recruiter_application_messages_path(1, 2)
=> "/recruiter/applications/1/messages.2"

>> app.recruiter_application_messages_path(1, Application.new)
=> "/recruiter/applications/1/messages"

所以我的猜测是这里存在路由冲突,application是一个新对象。这是很多ifs,但我认为这是你目前的情况。要使用通过命名空间声明的路由,请确保application是持久对象并将form_for更改为

form_for [:recruiter, application, Message.new], remote: true do |f|

对于第二个form_for,我想你只是忘了传递第一个参数,即新的消息对象

form_for Message.new, url: recruiter_application_messages_path(application.id)