2014-01-22 23 views
1

我有一個友好模型,允許用戶在我的Rails應用程序中成爲朋友。它存儲以下數據:Rails控制器方法在「if」和「else」語句中執行代碼

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

以下控制器方法是添加朋友

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 

會發生什麼事是請求被髮送的朋友,它會在那裏在數據庫中,當我切換到其他用戶的請求將在那裏,但在請求發送後彈出的通知和頁面重新加載說「已經與這個人或友誼的朋友等待接受。」就好像請求並未實際發送一樣,即使它是。即使數據庫中的所有友誼已被刪除,也會發生這種情況。

有關爲什麼會發生這種情況的任何想法?我希望它在發送時發送「發送好友請求」,而不是現在發送的內容。

回答

0

redirect_to不從方法返回並繼續執行。

你需要做的:

redirect_to root_path and return 

或:

return redirect_to root_path 
+0

它沒有爲我工作。我試過兩種情況。我所做的最終嘗試是改變從'get'到'post'的路線,但這並不起作用,所以我將它切換回'get',然後它第一次運作,但只有第一次。怪異的 – user2943464

0

試試這個

redirect_to的:控制器=> ...,:動作=> ...。

例如
DEF更新
@提示= current_user.tips.find(PARAMS [:ID])
@ tip.attributes =參數[:尖端]
@ tip.category_ids =參數[:類別]
@ tip.tag_with(PARAMS [:標籤])如果PARAMS [:標籤]

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