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

質問編集履歴

1

修正

2021/09/15 09:54

投稿

naoki1128
naoki1128

スコア3

title CHANGED
File without changes
body CHANGED
@@ -74,6 +74,83 @@
74
74
  </div>
75
75
  ```
76
76
 
77
+ ###Postコントローラー
78
+ ```ruby
79
+ class PostsController < ApplicationController
80
+ before_action :authenticate_user!
81
+
82
+ def index
83
+ @posts = Post.order("created_at DESC").limit(5)
84
+ end
85
+
86
+ def new
87
+ @post = Post.new
88
+ end
89
+
90
+ def create
91
+ @post = Post.create(post_params)
92
+ if @post.save
93
+ redirect_to root_path
94
+ else
95
+ render :new
96
+ end
97
+ end
98
+
99
+ def show
100
+ @post = Post.find(params[:id])
101
+ @comment = Comment.new
102
+ @comments = @post.comments.includes(:user)
103
+ end
104
+
105
+ def edit
106
+ @post = Post.find(params[:id])
107
+ end
108
+
109
+ def update
110
+ post = Post.find(params[:id])
111
+ post.update(post_params)
112
+ if post.save
113
+ redirect_to root_path
114
+ end
115
+ end
116
+
117
+ def destroy
118
+ post = Post.find(params[:id])
119
+ post.destroy
120
+ if post.destroy
121
+ redirect_to root_path
122
+ end
123
+ end
124
+
125
+ def prefecture
126
+ @post = Post.find_by(prefecture_id: params[:id])
127
+ @posts = Post.where(prefecture_id: params[:id]).order('created_at DESC')
128
+ end
129
+
130
+
131
+ private
132
+ def post_params
133
+ params.require(:post).permit(:title, :text, :prefecture_id, images: []).merge(user_id: current_user.id)
134
+ end
135
+ ```
136
+ ###Postモデル
137
+ ```ruby
138
+ class Post < ApplicationRecord
139
+ validates :title, presence: true
140
+ validates :text, presence: true
141
+ validates :prefecture_id, numericality: { other_than: 1 , message: "can't be blank"}
142
+ validates :images, presence: true
143
+
144
+ belongs_to :user
145
+ has_many :comments
146
+ has_many :likes, dependent: :destroy
147
+ has_many :liking_users, through: :likes, source: :user
148
+ has_many_attached :images
149
+ extend ActiveHash::Associations::ActiveRecordExtensions
150
+ belongs_to :prefecture
151
+ end
152
+ ```
153
+
77
154
  ### 試したこと
78
155
 
79
156
  https://qiita.com/tochisuke221/items/bff7d930ae282552ef77