1日1%成長するブログ

毎日成長するために仕事/プライベートで得た学びをアウトプットするブログです

Railsでコメント機能を作る

ルーティングの追加

resources :diaries do
  resources :comments, only: [:create]
end

コントローラー側

@diaryComment = DiaryComment.new(diary_comment_params)
@diaryComment.user_id = User.first.id
respond_to do |format|
  if @diaryComment.save
    format.html { redirect_to diaries_url, notice: 'Diary was successfully created.' }
    format.json { render :show, status: :created, location: @diaryComment }
  else
    format.html { redirect_to diaries_url }
    format.json { render json: @diaryComment.errors, status: :unprocessable_entity }
  end
end

def diary_comment_params
  # params.require(:diary).permit(:content)
  params.require(:diary_comment).permit(:content, :diary_id)
end

フォームの追加

= form_for([diary, diary.diary_comments.build]) do |f|
  %img.img-responsive.img-circle.img-sm{:alt => "Alt Text", :src => "xxxx"}/
  / .img-push is used to add margin to elements next to floating images
  .img-push
    = f.hidden_field :diary_id
    = f.text_field :content, class: "form-control input-sm", placeholder: "コメントを入力"

ポイント

  • 1:多のform_forの指定
  • ネストしたリソースのルーティング

今回はAjaxとしては実装しなかったのでまたそれは次回