Ruby on Rails チュートリアル 第6版 第7章 演習 解答

## 7.1.1 デバッグとRails環境

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/90217/9bc7a8ff-d54a-6fec-34a1-48d36f339b9e.png)

コントローラー： static_pages
アクション： about

```ruby
>> user = User.first
  User Load (0.8ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<User id: 1, name: "new man 2", email: "michael@example.com", created_at: "2022-01-15 18:29:55", updated_at: "2022-01-15 18:42:31", password_digest: [FILTERED]>
>> puts user.attributes.to_yaml
---
id: 1
name: new man 2
email: michael@example.com
created_at: !ruby/object:ActiveSupport::TimeWithZone
  utc: &1 2022-01-15 18:29:55.109680000 Z
  zone: &2 !ruby/object:ActiveSupport::TimeZone
    name: Etc/UTC
  time: *1
updated_at: !ruby/object:ActiveSupport::TimeWithZone
  utc: &3 2022-01-15 18:42:31.436070000 Z
  zone: *2
  time: *3
password_digest: "$2a$12$0FYGfdBHyNHjHw3q87aTweJs1b7cFACcVLa3kJZjuaasN8JqwNXs2"
=> nil
>> y user.attributes
---
id: 1
name: new man 2
email: michael@example.com
created_at: !ruby/object:ActiveSupport::TimeWithZone
  utc: &1 2022-01-15 18:29:55.109680000 Z
  zone: &2 !ruby/object:ActiveSupport::TimeZone
    name: Etc/UTC
  time: *1
updated_at: !ruby/object:ActiveSupport::TimeWithZone
  utc: &3 2022-01-15 18:42:31.436070000 Z
  zone: *2
  time: *3
password_digest: "$2a$12$0FYGfdBHyNHjHw3q87aTweJs1b7cFACcVLa3kJZjuaasN8JqwNXs2"
=> nil
```

## 7.1.2 Usersリソース

```/sample_app/app/views/users/show.html.erb
<%= @user.name %>, <%= @user.email %>
<%= @user.created_at %>, <%= @user.updated_at %>,<%= Time.now %>
```

## 7.1.3 debuggerメソッド

```ruby
(byebug) puts params.to_yaml
--- !ruby/object:ActionController::Parameters
parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  controller: users
  action: show
  id: '1'
permitted: false
nil
```

```ruby
(byebug) @user
nil
```

## 7.1.4 Gravatar画像とサイドバー

```ruby
>> user2 = User.new(name: "(略)", email: "(略)", password: "pass1234", password_confirmation: "pass1234")
=> #<User id: nil, name: "(略)", email: "(略)", created_at: nil, updated_at: nil, password_digest: [FILTERED]>
>> user2.id
=> nil
>> user2.valid?
  User Exists? (0.3ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) LIMIT ?  [["email", "(略)"], ["LIMIT", 1]]
=> true
>> user2.save
   (0.1ms)  begin transaction
  User Exists? (0.2ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) LIMIT ?  [["email", "(略)"], ["LIMIT", 1]]
  User Create (3.4ms)  INSERT INTO "users" ("name", "email", "created_at", "updated_at", "password_digest") VALUES (?, ?, ?, ?, ?)  [["name", "(略)"], ["email", "(略)"], ["created_at", "2022-01-16 11:33:41.340601"], ["updated_at", "2022-01-16 11:33:41.340601"], ["password_digest", "$2a$12$Nu672Jr1Bux0VpBP7Me4jOn6vJD.INNfWGio9AFnyOAaWziyP1hEK"]]
   (6.7ms)  commit transaction
=> true
>> user2.id
=> 2
```

→ /users/2 にアクセスして確認

## 7.2.1 form_withを使用する

```app/views/users/new.html.erb
<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_with(model: @user, local: true) do |foobar| %>
      <%= foobar.label :name %>
      <%= foobar.text_field :name %>

      <%= foobar.label :email %>
      <%= foobar.email_field :email %>

      <%= foobar.label :password %>
      <%= foobar.password_field :password %>

      <%= foobar.label :password_confirmation, "Confirmation" %>
      <%= foobar.password_field :password_confirmation %>

      <%= foobar.submit "Create my account", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>
```


## 7.2.2 フォームHTML

HTML編を購入していないため、スキップ

## 7.3.1 正しいフォーム

（演習なし）

## 7.3.2 Strong Parameters

```yaml
--- !ruby/object:ActionController::Parameters
parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  admin: '1'
  controller: users
  action: new
permitted: false
```

## 7.3.3 エラーメッセージ

```app/models/user.rb
  validates :password, presence: true, length: { minimum: 5 }
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/90217/1c1c7c84-ec23-8485-3bbd-8c71c05b8599.png)

未送信のユーザー登録フォームのURL： /signup (users#new)
送信済みのユーザー登録フォームのURL：　/users (users#create)

未送信のユーザ登録フォームへのリンクは signup_path であり、 users#new に遷移する。
送信済みのユーザー登録フォームは /users への遷移であり、バリデーションに失敗することで users#create を経由して、結局は users#new がレンダリングされている。

## 7.3.4 失敗時のテスト

```test/integration/users_signup_test.rb
require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest

  test "invalid signup information" do
    get signup_path
    assert_no_difference 'User.count' do
      post users_path, params: { user: { name:  "",
                                         email: "user@invalid",
                                         password:              "foo",
                                         password_confirmation: "bar" } }
    end
    assert_template 'users/new'
    assert_select 'div#error_explanation'
    assert_select 'div.field_with_errors'
  end
end
```

## 7.4.1 登録フォームの完成

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/90217/9b686948-1d63-143a-1bbb-9ff23a7656ad.png)

```ruby
$ rails c
Running via Spring preloader in process 21935
Loading development environment (Rails 6.0.3)
>> user = User.find_by_name("form")
   (0.9ms)  SELECT sqlite_version(*)
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."name" = ? LIMIT ?  [["name", "form"], ["LIMIT", 1]]
=> #<User id: 3, name: "form", email: "form@example.jp", created_at: "2022-01-16 14:04:35", updated_at: "2022-01-16 14:04:35", password_digest: [FILTERED]>
```

```ruby
--- !ruby/object:ActionController::Parameters
parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  controller: users
  action: show
  id: '3'
permitted: false
```

```ruby
--- !ruby/object:ActionController::Parameters
parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  controller: users
  action: show
  id: '4'
permitted: false
```

## 7.4.2 flash

## 7.4.3 実際のユーザー登録

## 7.4.4 成功時のテスト


## 7.5.1 本番環境でのSSL

## 7.5.2 本番環境用のWebサーバー


## 7.5.3 本番データベースを設定する




## リンク
[第6章Railsチュートリアル演習問題と解答まとめ](https://yukitoku-sw.hatenablog.com/entry/2019/10/23/233242)
[第7章Railsチュートリアル演習問題と解答まとめ](https://yukitoku-sw.hatenablog.com/entry/2019/10/26/201110)