Search code examples
putlink-tonested-resources

link_to update for a nested resource not working


The link in _applicant.html.erb looks like this in the browser: http://localhost:3000/needs/3/applicants.1 and when clicked on this shows up in the browser:

Routing Error

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

I want it to update the acceptance column for this particular applicant row. Basically I want it to send data to the update method of the applicants controller. How can I modify the code to do this?

_applicant.html.erb

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

got this from running rake routes:

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

Solution

  • I think there are two possible fixes here:

    First,

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

    should probably read

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

    The error is in this line:

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

    where...

    need_applicants_path(applicant.need_id, applicant.id)
    

    You can try passing in two instance objects like so:

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

    Second, another possible solution is to explicitly set the PUT path in your routes.

    In your config/routes.rb add the line

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

    then run

    rake routes
    

    and see what the PUT path is