###前提・実現したいこと
Ruby(Ruby on Rails)でブログサイトを作っています。
ログインユーザーがコメントをするような仕組みと想定しているのですが、どのようにして記事と関連づけるべきであるか迷っています。
ユーザーと記事に紐づいたコメントの登録を実装するうえで、表示されている記事にコメントを関連づけるためにはどうすればいいですか?
###該当のソースコード
・コメントコントローラー
Ruby
1class CommentsController < ApplicationController 2 3 def create 4 @comment = current_user.comments.build(comment_params) 5 if @comment.save 6 flash[:success] = "コメントが投稿されました!" 7 redirect_to root_path 8 else 9 @feed_items = [] 10 redirect_to root_path 11 end 12 end 13 14 def comment_params 15 params.require(:comment).permit(:content) 16 end 17end
・マイグレーションファイル
Ruby
1class CreateComments < ActiveRecord::Migration[5.0] 2 def change 3 create_table :comments do |t| 4 t.text :content 5 t.references :user, foreign_key: true 6 t.references :article, foreign_key: true 7 8 t.timestamps 9 end 10 add_index :comments, [:user_id, :article_id, :created_at] 11 end 12end
・コメントモデル
Ruby
1class Comment < ApplicationRecord 2 belongs_to :user 3 belongs_to :article 4 default_scope -> { order(created_at: :desc)} 5 validates :user_id, presence: true 6 validates :article_id, presence: true 7end
・ビュー
Ruby
1<%= form_for(@comment) do |f| %> 2 <%= render 'shared/error_messages', object: f.object %> 3 <div class="field"> 4 <%= f.text_area :content, placeholder: "コメントを入力する" %> 5 </div> 6 <%= f.submit "コメントする", class: "btn btn-primary" %> 7<% end %>
###試したこと
・ここからどうやって進めればよいのか見当がつかず、いっさい進められておりません。
###補足情報(言語/FW/ツール等のバージョンなど)
開発環境:Ruby on Rail 5.0.0.1
###追記情報(該当ソース)
・ビュー(articles/show.html.erb)
・・・ <section> <div class="title"> <h2>コメント</h2> <% if logged_in? %> <div class="row"> <aside class="col-md-4"> <section class="cooment_form"> <%= render 'shared/comment_form' %> </section> </aside> </div> <% else %> <div></div> <% end %> <%= render 'shared/feed' %> </section> ・・・
・ビュー(shared/comment_form)
Ruby
1 2<%= form_for(@comment) do |f| %> 3 <%= render 'shared/error_messages', object: f.object %> 4 <div class="field"> 5 <%= f.text_area :content, placeholder: "コメントを入力する" %> 6 </div> 7 <%= f.submit "Post", class: "btn btn-primary" %> 8<% end %>
・ビュー(shared/feed)
Ruby
1<%if @feed_items.any? %> 2 <%= render @feed_items %> 3 <%= will_paginate @feed_items %> 4<% end %>
・コントローラー(artcles/controller)
Ruby
1class ArticlesController < ApplicationController 2 before_action :comment_feed, only:[:show, :comment] 3 4 def show 5 end 6 7 def search 8 @articles = Article.paginate(page: params[:page]) 9 @categories = Category.all 10 end 11 12 def new 13 @article = Article.new(create_params) 14 end 15 16 private 17 18 def article_params 19 params.require(:space).permit(:title, :content) 20 end 21 22 def set_article 23 @article = Article.find(params[:id]) 24 end 25 26 def comment_feed 27 if logged_in? 28 @comment = current_user.comments.build 29 @feed_items = current_user.feed.paginate(page: params[:page]) 30 end 31 end 32end


回答1件
あなたの回答
tips
プレビュー