0
0

【Railsチュートリアル】第11-14章 まとめ

Last updated at Posted at 2024-03-23

第11章

コンソールの改行

ターミナル

rails generate migration add_activation_to_users \
> activation_digest:string activated:boolean activated_at:datetime

メーラーの生成

ターミナル

rails generate mailer UserMailer account_activation password_reset

メールを即時送信

app/controllers/users_controller.rb

UserMailer.account_activation(@user).deliver_now

メッセージを渡し、動作させる

app/models/user.rb


digest = self.send("#{attribute}_digest")

コントローラのアクション内で定義された変数をテストで使う

app/models/user.rb


@user = assigns(:user)

メールの宛先と件名を決める

app/mailers/user_mailer.rb

mail to: user.email, subject: "Account activation"

第12章

コンソールの改行

ターミナル

rails generate migration add_activation_to_users \
> activation_digest:string activated:boolean activated_at:datetime

隠しフィールドとしてページ内に保存する

app/views/password_resets/edit.html.erb

<%= hidden_field_tag :email, @user.email %>

第13章

データベースに反映させず、オブジェクトを返す

test/models/micropost_test.rb

@micropost = @user.microposts.build(content: "Lorem ipsum")

スコープを設定する

app/models/micropost.rb

default_scope -> { order(created_at: :desc) }

Procをの処理を評価する

ターミナル

>> -> { puts "foo" }
=> #<Proc:0x007fab938d0108@(irb):1 (lambda)>
>> -> { puts "foo" }.call
foo

紐づいたデータもあわせて削除する

app/models/user.rb

has_many :microposts, dependent: :destroy

アップロードファイルを関連づける

app/models/micropost.rb

has_one_attached :image

第14章

ユーザーidを指定してメンバーを表示

app/models/micropost.rb

resources :users do
  member do
    get :following, :followers
  end
end

ユーザーidを指定せずメンバーを表示

app/models/micropost.rb

resources :users do
  collection do
    get :tigers
  end
end

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