在Twitter上使用可追踪的宝石

时间:2018-10-21 15:35:57

标签: ruby-on-rails erb acts-as-follower

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

2 个答案:

答案 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上的followunfollow动作添加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