这节用于实现关注功能,分两种:
1.常规方式实现:
app/controllers/relationships_controller.rb
- class RelationshipsController < ApplicationController
- before_action :signed_in_user
- def create
- @user = User.find(params[:relationship][:followed_id])
- current_user.follow!(@user)
- redirect_to @user
- end
- def destroy
- @user = Relationship.find(params[:id]).followed
- current_user.unfollow!(@user)
- redirect_to @user
- end
- end
2.Ajax方式实现
使用 Ajax 后的关注用户表单
app/views/users/_follow.html.erb
- <%= form_for(current_user.relationships.build(followed_id: @user.id),
- remote: true) do |f| %>
- <div><%= f.hidden_field :followed_id %></div>
- <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
- <% end %>
使用 Ajax 后的取消关注用户表单
app/views/users/_unfollow.html.erb
- <%= form_for(current_user.relationships.find_by(followed_id: @user),
- html: { method: :delete },
- remote: true) do |f| %>
- <%= f.submit "Unfollow", class: "btn btn-large" %>
- <% end %>
在 Relationships 控制器中响应 Ajax 请求
app/controllers/relationships_controller.rb
- class RelationshipsController < ApplicationController
- before_action :signed_in_user
- def create
- @user = User.find(params[:relationship][:followed_id])
- current_user.follow!(@user)
- respond_to do |format|
- format.html { redirect_to @user }
- format.js
- end
- end
- def destroy
- @user = Relationship.find(params[:id]).followed
- current_user.unfollow!(@user)
- respond_to do |format|
- format.html { redirect_to @user }
- format.js
- end
- end
- end
创建关注“关系”的 JS-ERb 代码
app/views/relationships/create.js.erb
- $("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
- $("#followers").html('<%= @user.followers.count %>')
销毁关注“关系”的 JS-ERb 代码
app/views/relationships/destroy.js.erb
- $("#follow_form").html("<%= escape_javascript(render('users/follow')) %>")
- $("#followers").html('<%= @user.followers.count %>')