Joshua E
Joshua E

Reputation: 384

Rails Routing Issue, No Route Matches for Actions I defined in the controller

So I am working through a book on Rails development right now, and I have run into a problem. I have a "Users" controller with a few actions. One of the actions I have defined in it is "follow" However, whenever I have tried to link to that in my view with the rails helper, it tells me that I do not have that route defined. Here is what my controller looks like:

class UsersController < ApplicationController   
def follow
    @user = User.find(params[:id])
    if current_user.follow!(@user)
        redirect_to @user, notice: "Follow successful!"
    else 
        redirect_to @user, alert: "Error following."
    end
end

I have tried linking to this in two ways. Here is the first:

<%= link_to "Follow", {action: 'follow'}, class: 'btn btn-default' %>

this produces the error: "No route matches {:action=>"follow", :controller=>"users", :id=>"2"}"

Here is the second way:

<%= link_to "Follow", follow_user_path(@user), class: 'btn btn-default' %>

this produces the message : "undefined method `follow_user_path' for #<#:0x007f8fb76bd570>"

even when i run rake routes, the path does not show up there, even though i have defined in my routes.rb file

resources :users

I am at a complete loss right now. What am I doing wrong?

Upvotes: 1

Views: 564

Answers (2)

Babar Al-Amin
Babar Al-Amin

Reputation: 3984

You haven't defined the routes. resources :users will only define RESTful routes which won't cover follow. To cover that, you can write it like this:

resources :users do
  member do
    get :follow
  end
end

It'll generate URLs like:

/users/USER_ID/follow

Then from view, you can link to it like this:

<%= link_to "Follow", follow_user_path(USER_ID), class: 'btn btn-default' %>

Be sure to replace USER_ID with an actual user id!

Upvotes: 2

Chris Ma
Chris Ma

Reputation: 1

From my understanding, looks like there's no follow route, so inside your routes.rb, you'll need to put something like this: get "/follow", to: "users#follow"

Upvotes: -1

Related Questions