ぞえの技術めも

Ruby on Rails勉強中

【170日目】【1日20分のRailsチュートリアル】【第12章】フォローしているユーザーの関連付けを追加する

Ruby on Railsチュートリアル(第3版)

今日は「12.1.4 フォローしているユーザー」から。

12.1.4 フォローしているユーザー

Railsは“followeds”というシンボル名を見て、これを“followed”という単数形に変え、 relationshipsテーブルのfollowed_idを使って対象のユーザーを取得してきます。しかし、12.1.1で指摘したように、user.followedsという名前は英語として不適切です。

ふと思ったけど英語として不適切な点をスルーすればこの辺の作業要らないのでは…!?
まぁuser.followedsって言語として気持ち悪いんだろうけどね。英語苦手な私には分かるような分からないような。

ここでは:sourceパラメーター (リスト12.10) を使用し、「following配列の元はfollowed idの集合である」ということを明示的にRailsに伝えます。

app/models/user.rb

  has_many :following, through: :active_relationships, source: :followed

リスト12.8で定義した関連付けにより、フォローしているユーザーを配列の様に扱えるようになりました。

user.followingでアクセスできるようになるのか。それは便利だ。

次に、followingで取得した集合をより簡単に取り扱うために、followやunfollowといった便利メソッドを追加しましょう。

メソッドも追加するのか。更に便利。

アプリケーション内でこれらのメソッドを実際に使うのはまだ先だそうだから、まずテストを作成する。

test/models/user_test.rb

  test "should follow and unfollow a user" do
    michael = users(:michael)
    archer  = users(:archer)
    assert_not michael.following?(archer)
    michael.follow(archer)
    assert michael.following?(archer)
    michael.unfollow(archer)
    assert_not michael.following?(archer)
  end

表12.1のメソッドを参考にしながら、followingによる関連付けを使ってfollow、unfollow、following?メソッドを実装していきましょう (リスト12.10)。このとき、可能な限りself (user自身を表すオブジェクト) を省略している点に注目してください。

きっちり書くとself.active_relationships.create()になるのか。
うーん、言われないと省略してるの忘れそう…。

app/models/user.rb

  # ユーザーをフォローする
  def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
  end

  # ユーザーをアンフォローする
  def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
  end

  # 現在のユーザーがフォローしてたらtrueを返す
  def following?(other_user)
    following.include?(other_user)
  end

テスト実行して問題ないことを確認。

$ bundle exec rake test
63 tests, 312 assertions, 0 failures, 0 errors, 0 skips

今日の学習時間は【24分】

次は「12.1.5 フォロワー」から。