确认(看似)现有路线的路由错误

时间:2013-06-18 19:04:12

标签: ruby-on-rails ruby

我正在复制看似相同的逻辑,但它不适用于我的某个模型。

在调查中,我有

查看

<% @surveys.each do |survey| %>
  ...
  <%= link_to 'Delete', survey, :confirm => 'Are you sure?', :method => :delete %>
<% end %>

控制器

def destroy
  @survey = Survey.find(params[:id])
  @survey.destroy

  respond_to do |format|
    format.html { redirect to '/' }
    format.json { head :no_content }
  end
end

删除功能正常。

但问题是,我有

查看

<% @questions.each do |question| %>
  ...
  <%= link_to 'Delete', question, :confirm => 'Are you sure?', :method => :delete %>
<% end %>

控制器

def destroy
  @survey = Survey.find(params[:survey_id])
  @question = Question.find(params[:id])
  @question.destroy

  respond_to do |format|
    format.html { redirect to @survey }
    format.json { head :no_content }
  end
end

这给了我错误:

  undefined method `question path' for #<#<Class:0x008ff2534....

当我删除link_to时,它可以很好地检索question及其属性。

将视图中的逻辑更改为更具体的内容,

<%= link_to "Delete", :controller => "questions", :action => "destroy", :id => question.id %>

我得到了更具体的错误。

No route matches {:controller=>"questions", :action=>"destroy", :id=>1}

运行rake routes,确认路径存在。

DELETE /surveys/:survey_id/questions/:id(.:format)    questions#destroy

这是我的routes.rb条目:

devise_for :users do
  resources :surveys do
    resources :questions do
      resources :responses
    end
  end
end

计算机不会出错,所以我做错了什么?

2 个答案:

答案 0 :(得分:2)

questions是嵌套资源,因此您还应将survey传递到路径:

<%= link_to 'Delete', [@survey, question], :confirm => 'Are you sure?', :method => :delete %>

假设您已设置@survey变量。

答案 1 :(得分:2)

问题是调查下的嵌套资源,因此您的路线需要反映出来。请注意,在rake路由输出中,有一个:survey_id参数作为路径的一部分。这是必需的。因此,您的链接需要如下所示:

<%= link_to "Delete", :controller => "questions", :action => "destroy", :survey_id => @survey.id, :id => question.id %>

或者,您可以使用Marek的路径,命名空间问题资源:

<%= link_to 'Delete', [@survey, question], :confirm => 'Are you sure?', :method => :delete %>