Closed ryohakjae114 closed 2 months ago
ユーザフォロー機能
テーブルを作成 rails g model Relationship follower_id:integer followed_id:integer
rails g model Relationship follower_id:integer followed_id:integer
def change create_table :relationships do |t| t.integer :follower_id, null: false t.integer :followed_id, null: false t.timestamps end add_index :relationships, :follower_id add_index :relationships, :followed_id add_index :relationships, [:follower_id, :followed_id], unique: true end
belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "User"
has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy, inverse_of: :follower
has_many :following, through: :active_relationships, source: :followed
* user.rbでフォロワー一覧を取得できるように設定 ```ruby has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy, inverse_of: :followed has_many :followers, through: :passive_relationships, source: :follower
user.rbにfollowメソッドを作成
def follow(followed_user) following << followed_user end
user.rbにunfollowメソッドを作成
def unfollow(follwed_user) active_relationships.find_by(followed_id: other_user.id).destroy end
followとunfollowアクションを作成 rails g controller Relationships
rails g controller Relationships
resources :relationships, only: %i[create destroy]
def create @user = User.find(params[:followed_id]) current_user.follow(@user) redirect_to posts_path end
def destroy @user = Relationship.find(params[:id]).followed current_user.unfollow(@user) redirect_to posts_path end
* 投稿一覧ページの各postの名前の隣に、「フォローする」ボタン、あるいは「フォローを外す」ボタンを置く ```ruby def follow?(followed_user) following.include?(followed_user) end
- unless current_user == post.user - if current_user.follow?(post.user) = button_to t('unfollow'), relationship_path(current_user.active_relationships.find_by(followed: post.user)), method: :delete - else = link_to t('follow'), relationships_path(followed_id: post.user), data: { turbo_method: :post }
def index @posts = Post.where(user: current_user.following) end
ユーザフォロー機能
テーブルを作成
rails g model Relationship follower_id:integer followed_id:integer
has_many :following, through: :active_relationships, source: :followed
user.rbにfollowメソッドを作成
user.rbにunfollowメソッドを作成
followとunfollowアクションを作成
rails g controller Relationships
def destroy @user = Relationship.find(params[:id]).followed current_user.unfollow(@user) redirect_to posts_path end