Skip to content

Instantly share code, notes, and snippets.

@kdmgs110
Last active September 14, 2018 09:10
Show Gist options
  • Save kdmgs110/d0d326bf3cbaaa25ff5299b7659809cc to your computer and use it in GitHub Desktop.
Save kdmgs110/d0d326bf3cbaaa25ff5299b7659809cc to your computer and use it in GitHub Desktop.
act_as_followerの日本語説明
#gemfileにacts_as_followerを追加して、bundleします。
source 'https://rubygems.org'
gem "acts_as_follower"
resources :users do
member do
get :follow
get :unfollow
end
end
#user.rbにacts_as_followable :フォローされる acts_as_follower:フォローするを追加します。
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :forms
has_many :understands
mount_uploader :photo, PhotoUploader
acts_as_followable #フォローされる
acts_as_follower #フォローする
end
#便利なメソッド紹介
A.following?(B) # AはBをフォロー中か。true or false
A.follow_count # Aがフォローしている人の数を数えます。
A.followers_count # Aをフォローしている人の数を数えます。
user.all_follows # Aをフォローしているすべてのオブジェクトのデータを取得します。
user.all_following #Aがフォローしている全てのオブジェクトを取得します。
#フォロー、アンフォローボタンを追加します。
<h1><%= @users.name %></h1>
<% if current_user != @users %> <%# 現在のユーザーがフォロー、アンフォローしようとする相手と同一でない場合 %>
<% if current_user.following?(@users) %> <%# following?は、@userをフォローしているかどうかのtrueかfalseで教えてくれます。tureの場合はすでにフォローしているので、フォローを止めます%>
<%= link_to "Unfollow", unfollow_user_path(@users) %> 
<% else %><%# false、つまりまだフォローしていない場合は新しくフォローします。%>
<%= link_to "Follow", follow_user_path(@users) %>
<% end %>
<% end %>
# ここは、フォロー・フォロワー数を、数え、またフォロワーの写真をすべて表示しようとしています。
<h3>フォロー数:<%= @users.follow_count%></h3> <%# 現在フォローしているユーザー数を数えることができます。%>
<% @users.all_following.each do |user| %> <%# すべてのフォローしているユーザーのデータを引っこ抜いてきます。 %>
<%= image_tag user.photo.url,class:"micro-photo" %>
<% end %>
<h3>フォロワー数:<%= @users.followers_count%></h3> <%# フォロワー数を数えます。 %>
<% @users.followers.each do |user| %> <%# すべてのフォロワーのデータを引っこ抜いてくる %>
<%= image_tag user.photo.url,class:"micro-photo" %>
<% end %>
# フォローメソッドと、アンフォローメソッドを定義します。
def follow 
@user = User.find(params[:id])
if current_user 
if current_user == @user #現在のユーザーが、これからフォローするユーザーと同一だった場合
flash[:error] = "You cannot follow yourself."
else #違う人の場合
current_user.follow(@user) #followしてくれるメソッド
flash[:notice] = "You are now following #{@user.name}."
redirect_to @user
end
else
redirect_to root_path
end
end
def unfollow
@user = User.find(params[:id])
if current_user
current_user.stop_following(@user) #followを外してくれるメソッド
flash[:notice] = "You are no longer following #{@user.name}."
redirect_to @user
else
flash[:error] = "You must <a href='/users/sign_in'>login</a> to unfollow #{@user.name}.".html_safe
redirect_to @user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment