1

我在 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

很简单。在视图中,我有

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

在路线中,

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

当我点击链接时,它抱怨:Missing template users/start_following

那么,如何让它在操作后停留在同一页面上?我想留在的视图页面是 Show view of the user is to be follow。例如:用户/{user_id}。只是重定向不是解决方案吗?我认为添加redirect_to {somewhere}会消除错误,但事实并非如此。

4

3 回答 3

3

我会重定向到有问题的用户。如果您使用的是标准资源丰富的路线,那么您可以这样做

redirect_to(@user_to_follow)

顺便说一句,通常认为让 GET 请求进行更改是不好的做法——人们通常对这些请求使用 put/patch/post/delete 请求。您可能会在用户没有实际点击链接的情况下与浏览器预取链接发生冲突。

于 2012-12-12T11:52:38.613 回答
3

尝试:

redirect_to :back, :notice => "successfully followed someone..."
于 2012-12-12T11:54:03.937 回答
2

redirect_to的,可以解决您的问题,我怀疑您忘记将其添加到unless

代码如下所示:

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
于 2012-12-12T11:52:59.017 回答