操作中缺少模板



我在UsersController中写了一个"follow"方法

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

那么,如何让它在操作后保持在同一页面上?我想停留的视图页面是要关注的用户的显示视图。例如:用户/{user_id}。简单地重定向不是解决方案吗?我以为添加redirect_to {somewhere}可以消除错误,但事实并非如此。

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

redirect_to(@user_to_follow)

顺便说一句,让 GET 请求进行更改通常被认为是不好的做法 - 人们通常对这些请求使用放置/补丁/发布/删除请求。您可能会遇到浏览器预取链接而用户没有实际点击它们的情况。

尝试:

redirect_to :back, :notice => "successfully followed someone..."

是的,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

最新更新