我在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
那么,如何让它在动作后保持在同一页面?
我想留下的视图页面是要遵循的用户的显示视图。
例如:users / {user_id}。简单地重定向不是一个解决方案?我认为添加redirect_to {somewhere}
会消除错误,但事实并非如此。
答案 0 :(得分:3)
我会重定向到相关用户。如果您使用标准的资源丰富的路线,那么您可以做
redirect_to(@user_to_follow)
除此之外,通常认为让GET请求进行更改是不好的做法 - 人们通常会使用put / patch / post / delete请求。如果浏览器没有用户实际点击链接,您可能会在预先获取链接时遇到问题。
答案 1 :(得分:3)
尝试:
redirect_to :back, :notice => "successfully followed someone..."
答案 2 :(得分: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