im试图在我的应用程序中添加关注者,以便用户可以关注其他用户,并且在tweets索引页面上仅显示当前用户tweets和他们关注的人的tweet。我目前在用户显示页面上有一个“关注”按钮,但我希望单击后它会变为“关注”,但没有任何变化。香港专业教育学院看了其他问题和文档,但没有运气。谢谢。
用户显示视图:
<% if current_user.following?(@user) %>
<%= button_to "Following", {action: "unfollow", id: @user.id}, method: "post", class: "btn btn-secondary btn_unfollow", remote: true %>
<% else current_user != @user %>
<%= button_to "Follow", {action: "follow", id: @user.id}, method: "post", class: "btn btn-primary btn_follow", remote: true %>
<% end %>
用户控制器:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@tweets = @user.tweets.order('created_at DESC')
authorize @user
end
def follow
@current_user.follow(@user)
@follow = Follow.find_by(follower: @current_user, followable: @user)
# @user = User.find(params[:id])
# current_user.follow(@user)
# current_user.follow(@user)
# redirect to user_path(@user)
# respond_to :js
end
def unfollow
@user = User.find(params[:id])
@current_user.stop_following(@user)
# current_user.stop_following(@user)
# redirect_to user_path(@user)
# respond_to :js
end
end
路线:
resources :users do
member do
get :follow
get :unfollow
end
end
答案 0 :(得分:0)
您正在通过执行remote:true
添加ajax响应。您需要添加一个follow.js.erb
和一个unfollow.js.erb
视图,以重新呈现您的局部视图。
答案 1 :(得分:0)
尝试从视图中删除remote: true
部分:
<% if current_user.following?(@user) %>
<%= button_to "Following", {action: "unfollow", id: @user.id}, method: "post", class: "btn btn-secondary btn_unfollow" %>
<% elsif current_user != @user %>
<%= button_to "Follow", {action: "follow", id: @user.id}, method: "post", class: "btn btn-primary btn_follow" %>
<% end %>
为post
上的follow
和unfollow
动作添加routes.rb
方法:
resources :users do
member do
post :follow
post :unfollow
end
end
如果您使用current_user
作为身份验证解决方案,请尝试在@current_user
中使用UsersController
而不是Devise
:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@tweets = @user.tweets.order('created_at DESC')
authorize @user
end
def follow
current_user.follow(@user)
@follow = Follow.find_by(follower: current_user, followable: @user)
# @user = User.find(params[:id])
# current_user.follow(@user)
# current_user.follow(@user)
# redirect to user_path(@user)
# respond_to :js
end
def unfollow
@user = User.find(params[:id])
current_user.stop_following(@user)
# current_user.stop_following(@user)
# redirect_to user_path(@user)
# respond_to :js
end
end