teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

編集・追加依頼の内容に従って情報を追記しました。

2019/10/13 09:53

投稿

bok_sakai
bok_sakai

スコア20

title CHANGED
File without changes
body CHANGED
@@ -6,9 +6,9 @@
6
6
 
7
7
  しかし調べても参考になりそうなサイトが見当たらなかったので、こちらで質問させていただきました。
8
8
 
9
- いただけると嬉しい
9
+ 投稿一覧ページの各投稿に、icon、nickname、user_nameを表示する方法をえていただけませんしょうか
10
10
 
11
- ### 該当のソスコード
11
+ ### 投稿一覧ペ
12
12
 
13
13
  ```
14
14
  #home.html.erb
@@ -21,6 +21,18 @@
21
21
  ```
22
22
 
23
23
  ```
24
+ #top_controller
25
+
26
+ class TopController < ApplicationController
27
+ def home
28
+ @post = Post.all.order(created_at: :desc)
29
+ end
30
+ end
31
+ ```
32
+
33
+ ### 投稿詳細ページ
34
+
35
+ ```
24
36
  #show.html.erb こちらでは表示できる
25
37
 
26
38
  <div class="posts-show-item">
@@ -29,5 +41,81 @@
29
41
  <%= @post.created_at %>
30
42
  </div>
31
43
  <%= link_to(@user.user_name, "http://localhost:3000/users/#{@user.id}") %>
32
- </div>
44
+ </div>
45
+ ```
46
+
47
+ ```
48
+ #post_controller
49
+
50
+ class PostController < ApplicationController
51
+ protect_from_forgery except: :update
52
+ before_action :ensure_correct_user,{only: [:edit,:update,:destroy]}
53
+
54
+
55
+ def show
56
+ @id = params[:id]
57
+ @post = Post.find_by(id: params[:id])
58
+ @user = User.find_by(id: @post.user_id)
59
+ end
60
+
61
+ def edit
62
+ @post = Post.find_by(id: params[:id])
63
+ end
64
+
65
+ def update
66
+ @post = Post.find_by(id: params[:id])
67
+ @post.content = params[:content]
68
+ @post.save
69
+ redirect_to("/")
70
+ end
71
+
72
+ def destroy
73
+ @post = Post.find_by(id: params[:id])
74
+ @post.destroy
75
+ redirect_to("/")
76
+ end
77
+
78
+ def ensure_correct_user
79
+ @post = Post.find_by(id:params[:id])
80
+ if @post.user_id != @current_user.id
81
+ flash[:notice] = "権限がありません"
82
+ redirect_to("/posts/index")
83
+ end
84
+ end
85
+
86
+ end
87
+
88
+ ```
89
+
90
+ ### post model 投稿テーブル
91
+ ```
92
+ #post.rb
93
+ class Post < ApplicationRecord
94
+ end
95
+ ```
96
+
97
+ ### User model
98
+
99
+ ```
100
+ #user.rb ユーザーテーブル
101
+
102
+ class User < ApplicationRecord
103
+ # Include default devise modules. Others available are:
104
+ # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
105
+ devise :database_authenticatable, :registerable,
106
+ :recoverable, :rememberable, :validatable
107
+
108
+ before_create{ self.nickname = username }
109
+
110
+ def user_name
111
+ "@#{self.username}"
112
+ end
113
+
114
+ def posts
115
+ return Post.where(user_id: self.id)
116
+ end
117
+
118
+ mount_uploader :icon, ImageUploader
119
+
120
+ end
33
121
  ```