質問編集履歴

2

コードの追加

2022/02/22 10:56

投稿

KENT1004
KENT1004

スコア77

test CHANGED
File without changes
test CHANGED
@@ -69,6 +69,53 @@
69
69
  end
70
70
  end
71
71
  ```
72
+
73
+ postコントローラー
74
+ ```ruby
75
+ class PostsController < ApplicationController
76
+ before_action :authenticate_user
77
+ def index
78
+ @posts = Post.all.order(created_at: :desc)
79
+ end
80
+ def show
81
+ @post = Post.find_by(id: params[:id])
82
+ @user = @post.user
83
+ @likes_count = Like.where(post_id: @post.id).count
84
+ end
85
+
86
+ def new
87
+ end
88
+
89
+ def create
90
+ @post = Post.new(posts_params)
91
+
92
+ if @post.save
93
+ flash[:notice] = "投稿完了"
94
+ redirect_to("/posts/index")
95
+ else
96
+ render("/posts/new")
97
+ end
98
+
99
+ end
100
+
101
+ def posts_params
102
+ #投稿内容をパラメータで受け取る
103
+ params.permit(:comment, :site, :url, :content, :tag).merge(user_id: @current_user.id)
104
+ end
105
+
106
+
107
+ def edit
108
+ @post = Post.find_by(id: params[:id])
109
+ end
110
+
111
+ def destroy
112
+ @post = Post.find_by(id: params[:id])
113
+ @post.destroy
114
+ redirect_to("/posts/index")
115
+ end
116
+ end
117
+
118
+ ```
72
119
  現在**post.user.image_name**の部分のimage_nameの部分が未定義というエラーが起きています。
73
120
  他のファイルでは@users.image_nameのような使い方で利用できています。
74
121
  **オブジェクト.オブジェクト?.メソッド**のような形の仕組みをイマイチ理解できていません。

1

コードの追加

2022/02/22 10:54

投稿

KENT1004
KENT1004

スコア77

test CHANGED
File without changes
test CHANGED
@@ -18,6 +18,57 @@
18
18
  </div>
19
19
 
20
20
  ```
21
+ user.rb モデル
22
+
23
+ ```ruby
24
+ class User < ApplicationRecord
25
+ validates :name, {presence: true, uniqueness: true}
26
+ validates :email, {presence: true, uniqueness: true}
27
+ validates :password, {presence: true}
28
+
29
+ def posts
30
+ return Post.where(user_id: self.id)
31
+ end
32
+ end
33
+ ```
34
+ post.rb モデル
35
+
36
+ ```ruby
37
+ class Post < ApplicationRecord
38
+ validates :content, {presence: true}
39
+ validates :user_id, {presence: true}
40
+
41
+ def user
42
+ return User.find_by(id: self.user_id)
43
+ end
44
+ end
45
+ ```
46
+
47
+ postテーブル
48
+ ```ruby
49
+ class CreatePosts < ActiveRecord::Migration[5.2]
50
+ def change
51
+ create_table :posts do |t|
52
+ t.text :comment
53
+ t.text :site
54
+ t.text :url
55
+ t.text :content
56
+ t.text :tag
57
+
58
+ t.timestamps
59
+ end
60
+ end
61
+ end
62
+
63
+ ```
64
+ postテーブル追加項目
65
+ ```ruby
66
+ class AddUserIdToPosts < ActiveRecord::Migration[5.2]
67
+ def change
68
+ add_column :posts, :user_id, :integer
69
+ end
70
+ end
71
+ ```
21
72
  現在**post.user.image_name**の部分のimage_nameの部分が未定義というエラーが起きています。
22
73
  他のファイルでは@users.image_nameのような使い方で利用できています。
23
74
  **オブジェクト.オブジェクト?.メソッド**のような形の仕組みをイマイチ理解できていません。