現在Railsの勉強をしていて、ツイッターのようにユーザーがお互いにフォロー、フォロー解除できる機能を実装しています。
私が使っている教材では、以下のような記述をして機能を実装すると書いてあるのですが、フォロー・フォロー解除を行うメゾットの内容が理解できません。
class User < ApplicationRecord before_save { self.email.downcase! } validates :name, presence: true, length: { maximum: 50 } validates :email, presence: true, length: { maximum: 255 }, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+.[a-z]+\z/i }, uniqueness: { case_sensitive: false } has_secure_password has_many :microposts has_many :relationships has_many :followings, through: :relationships, source: :follow has_many :reverses_of_relationship, class_name: 'Relationship', foreign_key: 'follow_id' has_many :followers, through: :reverses_of_relationship, source: :user def follow(other_user) unless self == other_user self.relationships.find_or_create_by(follow_id: other_user.id) end end def unfollow(other_user) relationship = self.relationships.find_by(follow_id: other_user.id) relationship.destroy if relationship end def following?(other_user) self.followings.include?(other_user) end end
疑問1:この解釈であっていますか?
def follow(other_user) unless self == other_user self.relationships.find_or_create_by(follow_id: other_user.id) end end
このコードは、selfとother_userの内容が違った場合、other_user.idからフォローされる側のユーザfollow_idを所得して、createでフォロワーのデータをbuild+saveして保存するという意味ですか?
この解釈であっていますか?
疑問2:other_userはなに?
def follow(other_user) unless self == other_user self.relationships.find_or_create_by(follow_id: other_user.id) end end
selfはuser.follow(other) を実行したとき user が代入される。
ではother_userにはどの値が代入されるのですか?
疑問3:頭にselfと付けるのはなぜですか?
def follow(other_user) unless self == other_user self.relationships.find_or_create_by(follow_id: other_user.id) end end
中間テーブルからfollow_idを参照するならselfってつけなくてもいいんじゃないですか?
疑問4:relationship.destroy if relationshipとは?
def unfollow(other_user) relationship = self.relationships.find_by(follow_id: other_user.id) relationship.destroy if relationship end
ここで出てくる、relationship.destroy if relationshipとはどういう意味ですか?
これはrelationship(中間テーブル)に値が存在すればdestroyするという意味であっていますか?
この場合のif文は通常こう記述するものなのですか?
それとも省略されてこうなっているのですか?
疑問5:self.followings.include?(other_user)とは?
def following?(other_user) self.followings.include?(other_user) end
include?は配列の要素に引数が含まれていればtrue、なければfalseを返すという意味だと思うのですが、
よくこの文の意味が理解できません。
このRailsのフォロー・フォロー解除についてわかる方、ぜひご教示お願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/03/18 01:05