Eric Baldwin
Eric Baldwin

Reputation: 3501

No route matches [GET] on a resource declared in the routes file

When I click a link generated by the following code in a view:

<%= link_to "Colleague", collaborators_path(member2_id: user.id,), :method => :post %>

I get the following error message:

No route matches [GET] "/collaborators"

However, I have the following line in my routes file:

resources :collaborators, only: [:create, :destroy]

And I have the following definition written out in the collaborators_controller:

  @collaboration = current_user.collaborations.build(:member2_id => params[:member2_id])
      if @collaboration.save
        flash[:notice] = "Added collaborator."
        redirect_to root_url
      else
        flash[:error] = "Unable to add collaborator."
        redirect_to root_url
      end

So shouldn't the path for creating a collaboration be found by the router?

Upvotes: 1

Views: 211

Answers (2)

mrcasals
mrcasals

Reputation: 1171

Looks like the :method => :post is being ignored because you are using a link. POST method is commonly used when submiting forms. Actually, POST method is used to send data from the browser to the server in order to add new records to a database. See the Wikipedia article on HTTP methods for more info, and also Rails Guides on Routing.

If what you are trying to do is adding someone as a Colleague (just like Twitter's "follow" action, or Facebook's "Like") then you need to create an small form with the user's id in a hidden field.

TL;DR: use a form to create a relation, for a link won't work :)

Upvotes: 1

Stuart M
Stuart M

Reputation: 11588

It's because you are using only: [:create, :destroy]. You'd need to include :index in that array for there to be a GET /collaborators route. See the Rails guide on Routing

And in order to use links with :method => :post, you'll need to be using Rails 3's unobtrusive Javascript feature.

Upvotes: 1

Related Questions