基于Turbo实现动态组件:关注计数无需刷新页面问题排查
实现Turbo驱动的关注计数动态更新
要解决关注后需刷新页面才更新粉丝/关注数的问题,核心是利用Turbo Stream在关注动作完成后,无刷新替换对应的计数组件。以下是具体实现步骤:
1. 重构计数为可复用局部模板
将粉丝数和关注数的渲染逻辑抽离成局部模板,方便在Turbo Stream中复用:
app/views/users/_followers_count.html.erb
<p>Followers: <strong> <%= turbo_frame_tag "followers_count_#{user.id}" do %> <%= user.followers_count || user.followers.count %> <!-- 优先用counter_cache字段,无则回退到count查询 --> <% end %> </strong> </p>
app/views/users/_following_count.html.erb
<p>Following: <strong> <%= turbo_frame_tag "following_count_#{current_user.id}" do %> <%= current_user.following_count || current_user.following.count %> <% end %> </strong> </p>
然后在原页面中替换为局部模板渲染:
<%= render 'users/followers_count', user: @user %> <%= render 'users/following_count' %>
2. 修改关注控制器,返回Turbo Stream响应
在处理关注/取消关注的控制器动作中,添加Turbo Stream格式的响应,直接更新对应的Turbo Frame:
app/controllers/follows_controller.rb
def create @user = User.find(params[:user_id]) current_user.follow(@user) # 假设你的关注逻辑是这个方法 respond_to do |format| format.turbo_stream do render turbo_stream: [ # 更新被关注者的粉丝数 turbo_stream.replace("followers_count_#{@user.id}", partial: 'users/followers_count', locals: { user: @user }), # 更新当前用户的关注数 turbo_stream.replace("following_count_#{current_user.id}", partial: 'users/following_count') ] end format.html { redirect_to @user, notice: '已成功关注' } end end def destroy @user = User.find(params[:user_id]) current_user.unfollow(@user) respond_to do |format| format.turbo_stream do render turbo_stream: [ turbo_stream.replace("followers_count_#{@user.id}", partial: 'users/followers_count', locals: { user: @user }), turbo_stream.replace("following_count_#{current_user.id}", partial: 'users/following_count') ] end format.html { redirect_to @user, notice: '已取消关注' } end end
3. 确保关注按钮使用Turbo提交
确保触发关注的按钮/链接由Turbo处理(默认Turbo已启用,无需额外配置,除非手动禁用):
<%= button_to "关注", follows_path(user_id: @user.id), method: :post %> <!-- 或用链接 --> <%= link_to "关注", follows_path(user_id: @user.id), method: :post %>
4. 优化性能:使用Counter Cache
为避免每次查询followers.count带来的性能损耗,建议在模型中添加counter_cache:
- 生成迁移添加计数字段:
rails generate migration AddFollowersCountToUsers followers_count:integer default:0 rails generate migration AddFollowingCountToUsers following_count:integer default:0 rails db:migrate
- 更新Follow模型:
class Follow < ApplicationRecord belongs_to :follower, class_name: 'User', counter_cache: :following_count belongs_to :followed, class_name: 'User', counter_cache: :followers_count end
这样user.followers_count和current_user.following_count会自动更新,无需手动调用count查询,性能更优。
内容的提问来源于stack exchange,提问作者Muhammad Zubair
相关产品推荐
相关产品推荐

