1

I wrote a "follow" method in UsersController

def start_following
    @user = current_user
    @user_to_follow = User.find(params[:id])
    unless @user_to_follow == @user
        @follow_link = @user.follow_link.create(:follow_you_id => @user_to_follow.id, :user_id => @user.id)
        @user.save
        flash[:start_following] = "You started following" + @user_to_follow.name 
    else
        flash[:cant_follow] = "You cannot follow yourself"
    end
end

Pretty simple. And In the view, I have

<%= link_to 'Follow', follow_user_path(@user) %>

In routes,

resources :users do
 member do
    get 'follow' => "users#start_following", :as => 'follow'

When I click on the link, it complains: Missing template users/start_following

So, how do I make it just stay on the same page after the action? The view page that I want to stay on is Show view of the user is to be followed. ex: users/{user_id}. Is simply redirecting not a solution? I thought adding redirect_to {somewhere} would get rid of the error, but it didn't.

Tigraine
  • 23,358
  • 11
  • 65
  • 110
Maximus S
  • 10,759
  • 19
  • 75
  • 154

3 Answers3

3

I would redirect to the user in question. If you are using the standard resourceful routes then you can just do

redirect_to(@user_to_follow)

As an aside it's generally considered bad practice to have GET requests that make changes - people normally use put/patch/post/delete requests for those. You can fall afoul of browsers pre-fetching links without the user actually clicking on them.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • Thank you for the side note. How do I make it a PUT request instead of GET? – Maximus S Dec 12 '12 at 23:15
  • Change your routes file to be a put rather then a get then either add :method => :put to your link_to (requires the rails javascript stuff) or make it a form (button_to can be a quick shortcut for that) – Frederick Cheung Dec 13 '12 at 07:33
3

try:

redirect_to :back, :notice => "successfully followed someone..."
Siwei
  • 19,858
  • 7
  • 75
  • 95
2

Yes redirect_to solves your problem, I suspect you forgot to add it to both branches of the unless

The code would look like this:

def start_following
    @user = current_user
    @user_to_follow = User.find(params[:id])
    unless @user_to_follow == @user
        @follow_link = @user.follow_link.create(:follow_you_id => @user_to_follow.id, :user_id => @user.id)
        @user.save
        flash[:start_following] = "You started following" + @user_to_follow.name 
    else
        flash[:cant_follow] = "You cannot follow yourself"
    end
    redirect_to @user_to_follow
end
Tigraine
  • 23,358
  • 11
  • 65
  • 110