前提・実現したいこと
プログラミングスクールに通うプログラミング初心者です。
現在、ruby on rails でフォロー機能を作成しています。
今回は困っていることとしまして、フォロワー数を表示させる記述方法がわからないということです。
発生している問題・エラーメッセージ
フォロワー数を表示させたい
![]
user_id はフォローしているユーザーで、follow_idはフォローされたユーザーです。
該当のソースコード
(routes.rb)
resources :relationships, only: [:create, :destroy]
通知機能ののマイグレーションファイルです。
(user.rb)
has_many :relationships has_many :followings, through: :relationships, source: :follow has_many :reverse_of_relationships, class_name: 'Relationship', foreign_key: 'follow_id' has_many :followers, through: :reverse_of_relationships, source: :user
(relationship.rb)
belongs_to :user belongs_to :follow, class_name: 'User' validates :user_id, presence: true validates :follow_id, presence: true
(message.rb)メッセージのモデル
has_many :notifications, dependent: :destroy
(room.rb)チャットルームのモデルです。
has_many :notifications, dependent: :destroy
relationships_controller.rb
before_action :set_user def create following = current_user.follow(@user) if following.save flash[:success] = 'ユーザーをフォローしました' redirect_to @user else flash.now[:alert] = 'ユーザーのフォローに失敗しました' redirect_to @user end end def destroy following = current_user.unfollow(@user) if following.destroy flash[:success] = 'ユーザーのフォローを解除しました' redirect_to @user else flash.now[:alert] = 'ユーザーのフォロー解除に失敗しました' redirect_to @user end end private def set_user @user = User.find(params[:follow_id]) end
(users/show.html.erb)
<%= render 'relationships/follow_button', user: @user %> <span>フォロー数:<%= @user.relationships.count %></span>
(_follow_button.html.erb)
<% if model.errors.any? %> <div class="error-alert"> <ul> <% model.errors.full_messages.each do |message| %> <li class='error-message'><%= message %></li> <% end %> </ul> </div> <% end %>
補足
user.show画面に フォロー中の数とフォロワーの数を表示させたいと考えており、
フォロー中の数は、@user.relationships.count で表示させることができたのですが、
フォロワー数を持ってきたいと考えた場合どのような記述をすれば持ってこれますでしょうか?
ご教授いただきたいです。
あなたの回答
tips
プレビュー