我已經實現了關注者/關注關係,我想擴展功能,即。在我目前的實現中,用戶'A'在用戶'B'之後沒有用戶'B'的確認。我想讓用戶'A'向用戶'B'發送請求,然後用戶'B'接受或拒絕它。希望它像Instagram模型而不是Facebook模型[用戶A向用戶B發送跟隨請求。如果用戶B接受請求,則用戶A跟隨用戶B並且用戶B不跟隨用戶A,這樣做是用戶B必須發送向用戶A的請求]。關注請求Ruby on Rails
我的文件:
schema.rb
class CreateFollowJoinTable < ActiveRecord::Migration
def change
create_table 'follows' do |t|
t.integer 'following_id', :null => false
t.integer 'follower_id', :null => false
t.boolean :accepted, default: false
t.timestamps null: false
end
add_index :follows, :following_id
add_index :follows, :follower_id
add_index :follows, [:following_id, :follower_id], unique: true
end
end
應用程序/模型/ follow.rb
class Follow < ActiveRecord::Base
belongs_to :follower, foreign_key: 'follower_id', class_name: 'User'
belongs_to :following, foreign_key: 'following_id', class_name: 'User'
end
應用程序/模型/ user.rb
has_many :follower_relationships, foreign_key: :following_id, class_name: 'Follow'
has_many :followers, through: :follower_relationships, source: :follower
has_many :following_relationships, foreign_key: :follower_id, class_name: 'Follow'
has_many :following, through: :following_relationships, source: :following
def follow(user_id)
following_relationships.create(following_id: user_id)
end
def unfollow(user_id)
following_relationships.find_by(following_id: user_id).destroy
end
路線.rb
post ':user_name/follow_user', to: 'relationships#follow_user', as: :follow_user
post ':user_name/unfollow_user', to: 'relationships#unfollow_user', as: :unfollow_user
應用程序/控制器/ relationships_controller.rb
class RelationshipsController < ApplicationController
def follow_user
@user = User.find_by! user_name: params[:user_name]
if current_user.follow @user.id
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
end
def unfollow_user
@user = User.find_by! user_name: params[:user_name]
if current_user.unfollow @user.id
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
end
end
井的Instagram,用戶可以隨後沒有任何要求的用戶。 – Pavan
您正在關注michael hartl的railstutorial.org對不對? – icemelt
否@icemelt我不是,即使在michael hartl的教程中,用戶也可以在沒有任何請求的情況下關注另一個 – Ashksta