user2943464
user2943464

Reputation: 57

Rails controller method executes code in both the "if" and "else" statement

I have a friendship model that allows users to become friends in my Rails app. It stores the following data:

friendship_id (int), sender_id (int), receiver_id (int), sent_at (datetime), accepted (boolean), accepted_at (datetime)

The following controller method is for adding friends

def addfriend
    if user_signed_in?
      @sender = params[:sender]
      @receiver = params[:receiver]
      if Friendship.find_by(sender_id: @sender, receiver_id: @receiver).nil? &&
        Friendship.find_by(sender_id: @receiver, receiver_id: @sender).nil?

        @friend = Friendship.create(friendship_id: 0, sender_id: @sender, receiver_id: @receiver, sent_at: DateTime.now, accepted: false)

        if @friend.save

          flash[:success] = "Friend request sent"
          redirect_to root_path
        else
          flash[:error] = "Oops, something went wrong."
          redirect_to root_path
        end

      else
        flash[:notice] = "Already friends with this person or friendship pending acceptance."
        redirect_to root_path
      end
    end
end

What happens is the friend request gets sent, it will be there in the database and when I switch to the other user the request will be there, but the notification that pops up after the request was sent and the page reloads says "Already friends with this person or friendship pending acceptance." As if the request wasn't actually sent, even though it was. This even happens when all Friendships have been deleted in the database.

Any thoughts as to why this is happening? I want it to say "Friend request sent" when it does get sent, rather than what it is saying now.

Upvotes: 1

Views: 85

Answers (2)

Sugat Mankar
Sugat Mankar

Reputation: 478

Try this

redirect_to :controller =>… , :action=>….

for example
def update
@tip = current_user.tips.find(params[:id])
@tip.attributes = params[:tip]
@tip.category_ids = params[:categories]
@tip.tag_with(params[:tags]) if params[:tags]

if @tip.save  
  flash[:notice] = 'Tip was successfully updated.'  
  redirect_to :controller=>'tips', :action => 'show', :id => @tip.permalink  
else  
  render :action => 'edit'  
end  

end

Upvotes: 0

manojlds
manojlds

Reputation: 301327

redirect_to doesn't return from the method and continues the execution.

You need to do:

redirect_to root_path and return

or:

return redirect_to root_path

Upvotes: 0

Related Questions