用错误的参数重定向

时间:2013-11-01 13:33:52

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个允许用户关注/取消关注其他用户的应用。此关系存储在relationships表中,该表包含字段idfollower_idfollowed_id。当我调用destroy方法取消关注用户时,它会破坏关系,但之后会尝试使用已销毁的关系id而不是用户id重定向回跟随的用户。此id存储在关系表的followed_id字段中。我不知道如何在铁轨上拍摄这个问题。

这是关系控制器

class RelationshipsController < ApplicationController
    def create
        @relationship = Relationship.new
        @relationship.followed_id = params[:followed_id]
        @relationship.follower_id = current_user.id
        if @relationship.save
            redirect_to User.find params[:followed_id]
        else
            flash[:error] = "Couldn't Follow"
            redirect_to root_url
        end
    end

    def destroy
        @relationship = Relationship.find(params[:id])
        @relationship.destroy
        redirect_to user_path params[:id]
    end
end

2 个答案:

答案 0 :(得分:3)

取代:

redirect_to user_path params[:id]

使用:

redirect_to user_path(@relationship.followed_id)

@relationship已从数据库中删除,但您仍然在内存中拥有该对象。

答案 1 :(得分:1)

def destroy
        @relationship = Relationship.find(params[:id])
        @followed_user_id = @relationship.followed_id
        @relationship.destroy
        redirect_to user_path @followed_user_id
    end

希望这可能有所帮助:)