link_to更新嵌套资源不起作用

时间:2013-06-17 02:55:14

标签: put link-to nested-resources

_applicant.html.erb中的链接在浏览器中显示如下:http://localhost:3000/needs/3/applicants.1 点击后显示在浏览器中:

Routing Error

No route matches [PUT] "/needs/3/applicants.1"

我希望它更新此特定申请人行的接受栏。基本上我希望它将数据发送到申请人控制器的更新方法。如何修改代码才能执行此操作?

_applicant.html.erb

<%= link_to 'Accept Applicant', need_applicants_path(applicant.need_id, applicant.id), :method => :put, :action => "update", :applicant => {:acceptance => true} %>

通过运行rake路线得到了这个:

PUT    /needs/:need_id/applicants/:id(.:format)      applicants#update

routes.rb中:

resources :needs, except: [:new] do
 resources :applicants
end

applicants_controller.rb

class ApplicantsController < ApplicationController

  def update
    @need = Need.find(params[:need_id])
    @applicant = @need.applicants.find(params[:id])

    if @applicant.update_attributes(params[:applicant])
      flash[:success] = 'Your applicant has been accepted/rejected!'
      redirect_to @need
    else
        @need = Need.find(params[:need_id])
      render 'needs/show'
    end

  end


end

1 个答案:

答案 0 :(得分:1)

我认为这里有两种可能的解决方法:

首先,

http://localhost:3000/needs/3/applicants.1

应该阅读

http://localhost:3000/needs/3/applicants/1

错误在这一行:

<%= link_to 'Accept Applicant', need_applicants_path(applicant.need_id, applicant.id), :method => :put, :action => "update", :applicant => {:acceptance => true} %>

其中...

need_applicants_path(applicant.need_id, applicant.id)

您可以尝试传入两个实例对象,如下所示:

need_applicants_path(Need.find(applicant.need_id), applicant)

其次,另一种可能的解决方案是在路线中明确设置PUT路径。

在你的config / routes.rb中添加一行

put 'need/:need_id/applicant/:id/update

然后运行

rake routes

并查看PUT路径是什么