はじめに
僕の質問サイトに回答機能とは別にコメント機能を追加したのでメモとして残しておきます。
初心者なので間違っていたらコメントで指摘していただけると幸いです。
前提
rails6
ruby2.7.0
questionモデル(投稿モデル)
Userモデル(deviseのもの)
はつくられている前提です。
コメントモデルを作る
$ rails g model comment comment:text comment_id:integer commenter_id:integer
$ rails db:migrate
カラム名通りcommentはコメントそのもの、comment_idはどの投稿に対してのコメントか、commenter_idは誰がコメントをしたかを保存します。
user.rb
has_many :comments, foreign_key: :commenter_id
questions.rb
has_many :comments
comment.rb
belongs_to :user
belongs_to :questions, optional: true
コントローラー作成
$ rails g controller comments
comments_controller.rb
class CommentsController < ApplicationController
def create
@comment = Comment.new(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to "/questions/#{@comment.comment_id}" }
else
format.html { render :new }
end
end
end
private
def comment_params
params.require(:comment).permit(:comment, :comment_id, :commenter_id)
end
end
ルーティング
resources :comments, only: [:create]
views
今回はエラーメッセージなどは表示しないようにしています。
comments/_form.html.erb
<%= form_with model: comment do |f| %>
<%= f.text_area :comment %>
<%= f.hidden_field :comment_id, { value:@question.id } %>
<%= f.hidden_field :commenter_id, { value:current_user.id } %>
<%= f.submit 'コメントをする' %>
<% end %>
questions_controller.rb
def show
@question = Question.find(params[:id])
@comment = Comment.new
@comments = Comment.where(comment_id: @question.id)
end
あとは表示したい場所(show.html.erb)などに
show.html.erb
<% @comments.each do |f| %> #コメント表示
<p><%= f.comment %></p>
<p><%= f.user.name %></p>
<% end %>
<%= render "comments/form", comment: @comment %> #フォーム
と書いてください。
終わりに
お疲れさまでした😃。結構仕組み自体は簡単ですが一からやるとなるとやはりエラーなどが見えてしまいました。
あとはエラー表示、削除、編集機能を実装してみるといいかもしれません。
宣伝
あと、最近ぼくが公開した資格試験の質問サイト QUAもお願いします。利用者がいません(泣)。