0
0

More than 1 year has passed since last update.

railsチュートリアル第13章 ユーザーのマイクロポスト

Posted at

ユーザーのマイクロポスト

マイクロポストを作成する

Micropostモデル

$ git checkout -b user-microposts

基本的なモデル

Micropostモデルは、2つだけの属性だけを持ちます。
・マイクロポストの内容を保存するcontent属性
・特定のユーザーとマイクロポストを関連付けるuser_id属性

マイクロポストの投稿にString型ではなくText型を使っている
本番環境ではtext,String型にパフォーマンスの差はない。

Micropostモデルを生成する

ubuntu:~/environment/sample_app (user-microposts) $ rails generate model Micropost content:text user:references
# user:references UserとMicropostを関連付けする下準備
Running via Spring preloader in process 3829
      invoke  active_record
      create    db/migrate/20211022055910_create_microposts.rb
      create    app/models/micropost.rb
      invoke    test_unit
      create      test/models/micropost_test.rb
      create      test/fixtures/microposts.yml

自動生成されたMicropostモデル

app/models/micropost.rb

class Micropost < ApplicationRecord
# ApplicationRecordを継承したモデルが作られます
  belongs_to :user
  # userモデルとの間に「1対1」のつながりが設定
  # 割り当てる
end

インデックスが付与されたMicropostのマイグレーション

db/migrate/[timestamp]_create_microposts.rb

class CreateMicroposts < ActiveRecord::Migration[6.0]
  def change
    create_table :microposts do |t|
    # create_table テーブルを作成
    # micropostsテーブルから1つ取り出す
      t.text :content
      # 
      t.references :user, null: false, foreign_key: true
      t.timestamps
    end
    add_index :microposts, [:user_id, :created_at]
  end
end

演習

1.
RailsコンソールでMicropost.newを実行し、インスタンスを変数micropostに代入してください。その後、user_idに最初のユーザーのidを、contentに "Lorem ipsum" をそれぞれ代入してみてください。この時点では、 micropostオブジェクトのマジックカラム(created_atとupdated_at)には何が入っているでしょうか?

>> micropost = Micropost.new
   (0.4ms)  SELECT sqlite_version(*)
=> #<Micropost id: nil, content: nil, user_id: nil, created_at: nil, updated_at: nil>
>> micropost.user_id = 1
=> 1
>> micropost.content = "Lerem ipsum"
=> "Lerem ipsum"
>> micropost 
=> #<Micropost id: nil, content: "Lerem ipsum", user_id: 1, created_at: nil, updated_at: nil>
>> micropost 

2.
先ほど作ったオブジェクトを使って、micropost.userを実行してみましょう。どのような結果が返ってくるでしょうか? また、micropost.user.nameを実行した場合の結果はどうなるでしょうか?

>> micropost.user
=> #<User id: 1, name: "Example User", email: "example@railstutorial.org", created_at: "2021-10-17 05:28:48", updated_at: "2021-10-20 14:25:39", password_digest: [FILTERED], remember_digest: nil, admin: true, activation_digest: "$2a$12$x4xVHmtrDFjVPFFWav31UebLY8r9sdT8ImzSXGSrnqt...", activated: true, activated_at: "2021-10-17 05:28:48", reset_digest: "$2a$12$FhfOA3Y7VPJ3TJJ5nNUEkuSH0hkGrrW15uyYE9EwbrC...", reset_sent_at: "2021-10-20 14:25:39">
>> micropost.user.name
=> "Example User"

3.
先ほど作ったmicropostオブジェクトをデータベースに保存してみましょう。この時点でもう一度マジックカラムの内容を調べてみましょう。今度はどのような値が入っているでしょうか?

>> micropost.save
   (0.1ms)  begin transaction
  Micropost Create (2.8ms)  INSERT INTO "microposts" ("content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["content", "Lerem ipsum"], ["user_id", 1], ["created_at", "2021-10-22 06:31:48.078604"], ["updated_at", "2021-10-22 06:31:48.078604"]]
   (9.4ms)  commit transaction
=> true

これで

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