Rails控制器方法在“if”和“else”语句中执行代码

时间:2014-01-22 05:09:48

标签: ruby-on-rails activerecord controller

我有一个友谊模型,允许用户在我的Rails应用程序中成为朋友。它存储以下数据:

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

朋友请求被发送后会发生什么,它将存在于数据库中,当我切换到其他用户时,请求将在那里,但是在发送请求并且页面重新加载后弹出的通知显示“已经是这个人或朋友的朋友,等待接受。“好像请求实际上没有发送,即使它是。即使在数据库中删除了所有友谊,也会发生这种情况。

有关为何发生这种情况的任何想法?我希望它在发送时发出“发送好友请求”,而不是现在说的话。

2 个答案:

答案 0 :(得分:0)

redirect_to不会从方法返回并继续执行。

你需要这样做:

redirect_to root_path and return

或:

return redirect_to root_path

答案 1 :(得分:0)

试试这个

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

例如,

def update
    @tip = current_user.tips.find(params [:id])
    @tick.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  

结束