这节用于实现关注功能,分两种:
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
使用 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 %>
<%= 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 %>
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
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>") $("#followers").html('<%= @user.followers.count %>')
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>") $("#followers").html('<%= @user.followers.count %>')