個人アプリ開発 コメント機能作成2
コメント投稿フォームの場所を、グループ詳細ページから、コメント作成用ページに変更
後々の仕様を考慮し変更しました
・routes.rb編集
・comments_controller編集
・view comment_new作成
記事詳細ページ view修正
コメントが仮のものだったので、DBから表示するように修正しました。
- @comments.each do |comment| - if comment.nil? .comment-none コメントはまだありません - else .aquarium-comments__wrapper .aquarium-comments__wrapper__user .aquarium-comments__wrapper__user__image .aquarium-comments__wrapper__user__name = comment.user.name .aquarium-comments__wrapper__comment .aquarium-comments__wrapper__comment__title = comment.title .aquarium-comments__wrapper__comment__text = comment.text .aquarium-comments__wrapper__comment--bottom .aquarium-comments__wrapper__comment--bottom__rate %p.rate ★★★★☆ .aquarium-comments__wrapper__comment--bottom__time 行った時期:#{comment.visit_date} - if comment.user.id == current_user.id .aquarium-comments__wrapper__comment--bottom__edit = link_to "編集", edit_group_comment_path(group_id: @group.id, id: comment.id) .aquarium-comments__wrapper__comment--bottom__delete = link_to "削除", group_comment_path(group_id: @group.id, id: comment.id), method: :delete
- if comment.nil?
コメントがない場合は”コメントはまだありません”のメッセージを表示
- if comment.user.id == current_user.id
自分のコメントには編集・削除に遷移できるリンクを設置しました。
編集・削除機能の作成
routes.rbの編集
resources :groups do resources :comments, only: [:new, :create, :edit, :update, :destroy] end
コントローラーの編集
[comments_controller] before_action :set_group def new @comment = Comment.new @comments = @group.comments.includes(:user) end def create @comment = Comment.create(comment_params) if @comment.save redirect_to group_path(@comment.group.id) else render :new end end def edit @comment = Comment.find(params[:id]) end def update @comment = Comment.find(params[:id]) if @comment.update(comment_params) redirect_to group_path(@comment.group.id) else render :edit end end def destroy @comment = Comment.find(params[:id]) @comment.destroy redirect_to group_path(@comment.group.id) end private def comment_params params.require(:comment).permit(:title, :text, :visit_date).merge(user_id: current_user.id, group_id: params[:group_id]) end def set_group @group = Group.find(params[:group_id]) end
ビューの作成
[comments_edit.html.haml] = render 'form'
躓き
コントローラーに変数が用意されてないことが原因でエラーを何度も出してしまいました。
ただ慌てずに一つずつ解決することができたと思います。
railsの基本の7つのアクションは何度も学んできてはいましたが、自分でエラーを出しながら考えて実装することで理解が深まっていく気がしました。
今後コメントの新規作成・編集を、オーバーレイとモーダルウィンドウを使用して表示できるように実装していきたいと思います。
→最終的にモーダルウィンドウに
https://qiita.com/takachan_coding/items/9179cf361d0e92ae0bad
http://exrecord.net/how-to-create-overlay-and-modal-window-in-jquery