LoginSignup
0
0

More than 1 year has passed since last update.

railsチュートリアル第十四章 ユーザーをフォローする

Posted at

ユーザーをフォローする

他のユーザーをフォロー(およびフォロー解除)できるソーシャルな仕組みの追加と、
フォローしているユーザーの投稿をステータスフィードに表示する機能を追加します。

ユーザー間の関係性をどうモデリングするかについて学びます
モデリング結果に対応するWebインターフェースを実装していきます。
このとき、Webインターフェースの例としてAjaxについても紹介します。最後に、ステータスフィードの完成版を実装します。

ステータスフィード作成のためにRuby/SQLを「だます」テクニックも含まれます。

これまでよりも複雑なデータモデルを使います。
ここで学んだデータモデルは、今後自分用のWebアプリケーションを開発するときに必ず役に立ちます。

モックアップ
工業製品の設計・デザイン段階で試作される、外見を実物そっくりに似せて作られた実物大の模型のこと。

Relationshipモデル

ユーザーをフォローする機能を実装する第一歩は、データモデルを構成することです。

git checkout -b following-users
ubuntu:~/environment/sample_app (following-users) $ rails generate model Relationship follower_id:integer followed_id:integer
Running via Spring preloader in process 4446
      invoke  active_record
      create    db/migrate/20211027060213_create_relationships.rb
      create    app/models/relationship.rb
      invoke    test_unit
      create      test/models/relationship_test.rb
      create      test/fixtures/relationships.yml

relationshipsテーブルにインデックスを追加する
db/migrate/[timestamp]_create_relationships.rb

class CreateRelationships < ActiveRecord::Migration[6.0]
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      # integer : 整数 
      # tを整数型のデータにする
      # それをfollewer_idカラムの値にする
      t.integer :followed_id

      t.timestamps
    end

    add_index :relationships, :follower_id
    # add_index 指定したテーブルにインデックスを追加
    # followingテーブルのそれぞれの行は、
    #   followed_idで識別可能なユーザーでなければなりません
    #  ユーザーを認識するための行
    # フォローする側
    add_index :relationships, :followed_id
    # フォローされる側
    # 
    add_index :relationships, [:follower_id, :followed_id], unique: true
    # follower_idとfollowed_idの組み合わせが必ずユニークであることを保証する仕組みです。
    # ユニーク 一意性制約(テーブル内で重複するデータを禁止する)
    #          カラムに独自性を与えます。
  end
end
rails db:migrate

演習

1.
図 14.7のid=1のユーザーに対してuser.following.map(&:id)を実行すると、結果はどのようになるでしょうか? 想像してみてください。ヒント: 4.3.2で紹介したmap(&:method_name)のパターンを思い出してください。例えばuser.following.map(&:id)の場合、idの配列を返します。

配列で返しそう。

2.
図 14.7を参考にして、id=2のユーザーに対してuser.followingを実行すると、結果はどのようになるでしょうか? また、同じユーザーに対してuser.following.map(&:id)を実行すると、結果はどのようになるでしょうか? 想像してみてください。

わからない。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0