質問編集履歴

4

before_actionについてコメントコメントアウトして使わないようにしています

2021/09/23 13:46

投稿

hiromix
hiromix

スコア7

test CHANGED
File without changes
test CHANGED
@@ -24,7 +24,9 @@
24
24
 
25
25
  class UsersController < ApplicationController
26
26
 
27
- before_action :set_user, only: ["index", "show"]
27
+ #before_action :set_user, only: ["index", "show"]
28
+
29
+ ※before_actionはよくわからないのでコメントアウトしています
28
30
 
29
31
 
30
32
 
@@ -45,6 +47,8 @@
45
47
  end
46
48
 
47
49
  ```
50
+
51
+
48
52
 
49
53
  他にも下記のように書いたりしています
50
54
 

3

def show 古い記述だったので改めて追加しました

2021/09/23 13:46

投稿

hiromix
hiromix

スコア7

test CHANGED
File without changes
test CHANGED
@@ -18,17 +18,39 @@
18
18
 
19
19
  controller
20
20
 
21
+
22
+
21
23
  ```
22
24
 
23
25
  class UsersController < ApplicationController
24
26
 
27
+ before_action :set_user, only: ["index", "show"]
28
+
29
+
30
+
31
+ def index
32
+
33
+ @users = User.all
34
+
35
+ end
36
+
37
+
38
+
25
39
  def show
26
40
 
27
- @users = User.all
41
+ @user = User.find_by(params[:account_name])
42
+
43
+
28
44
 
29
45
  end
30
46
 
31
47
  ```
48
+
49
+ 他にも下記のように書いたりしています
50
+
51
+ @user = User.find_by(params[:name])
52
+
53
+ @user = User.find(params[:id])
32
54
 
33
55
 
34
56
 

2

modelとroutes追加しました

2021/09/23 13:29

投稿

hiromix
hiromix

スコア7

test CHANGED
File without changes
test CHANGED
@@ -14,6 +14,10 @@
14
14
 
15
15
  ```
16
16
 
17
+
18
+
19
+ controller
20
+
17
21
  ```
18
22
 
19
23
  class UsersController < ApplicationController
@@ -23,6 +27,64 @@
23
27
  @users = User.all
24
28
 
25
29
  end
30
+
31
+ ```
32
+
33
+
34
+
35
+ routes
36
+
37
+ ```
38
+
39
+ Rails.application.routes.draw do
40
+
41
+
42
+
43
+ devise_for :users
44
+
45
+ root 'users#index'
46
+
47
+ resources :users, only: [:show,:index,:edit,:update,:destroy]
48
+
49
+ end
50
+
51
+ ```
52
+
53
+
54
+
55
+ model
56
+
57
+ ```
58
+
59
+ class User < ApplicationRecord
60
+
61
+ # Include default devise modules. Others available are:
62
+
63
+ # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
64
+
65
+ devise :database_authenticatable, :registerable,
66
+
67
+ :recoverable, :rememberable, :validatable
68
+
69
+
70
+
71
+ validates :account_name,
72
+
73
+ uniqueness: true,
74
+
75
+ format: { with: /\A[a-zA-Z\d]+\z/ },
76
+
77
+ length: { minimum: 3, maximum: 25 }
78
+
79
+
80
+
81
+ def to_param
82
+
83
+ return self.account_name
84
+
85
+ end
86
+
87
+ end
26
88
 
27
89
  ```
28
90
 

1

User.find(params[:id]) だとユーザー名が表示されました

2021/09/23 07:42

投稿

hiromix
hiromix

スコア7

test CHANGED
File without changes
test CHANGED
@@ -76,4 +76,14 @@
76
76
 
77
77
  上記で問題なく動くので、user.nameをusers/showでも使えるものかと思っていましたが使えません。
78
78
 
79
+
80
+
81
+ ただ、
82
+
83
+ `@user = User.find(params[:id])`にして http://localhost:3000/users/9 などでそのページに移動すると、ユーザー名は表示されます。
84
+
85
+
86
+
87
+
88
+
79
89
  どなたかお詳しい方ご教授お願い致しますm(__)m