質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby on Rails 5

Ruby on Rails 5は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Q&A

解決済

1回答

835閲覧

Railsでコメントとユーザーの紐付けができない

Shmupeiii

総合スコア105

Ruby on Rails 5

Ruby on Rails 5は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

0グッド

0クリップ

投稿2022/02/24 05:04

編集2022/02/24 12:42

Ruby on Railsを使った掲示板サイトのポートフォリオを作成しています。

heroku
https://rails-docker-portfolio.herokuapp.com/
ログインid sample123
ログインパスワード sample12345
github
https://github.com/takoyan33/rails-docker

そこで、今掲示板のコメントをログインユーザーのみでできるようにしたく、コメントをすると、現在ログインしている人の名前とコメントが表示されるようにしたいと考えています。

掲示板とユーザーの紐付けとコメント投稿機能はできているんですが、ユーザーとコメントの紐付けができておらず、エラーが出てしまいます。

対処法が分かる方がいればよろしくお願いします。

Railsバージョンは、5.2.2です。

サンプル例(ログインするとコメントできるようにしたいという感じです。)
https://rails-docker-portfolio.herokuapp.com/boards/74

#本番環境でのエラー 2022-02-24T04:49:24.711405+00:00 app[web.1]: I, [2022-02-24T04:49:24.711377 #18] INFO -- : [4553c434-3014-4ac6-abe4-fef61709f990] Completed 200 OK in 50ms (Views: 15.3ms | ActiveRecord: 19.6ms) 2022-02-24T04:49:24.713945+00:00 heroku[router]: at=info method=GET path="/boards/74" host=rails-docker-portfolio.herokuapp.com request_id=4553c434-3014-4ac6-abe4-fef61709f990 fwd="124.110.129.63" dyno=web.1 connect=0ms service=53ms status=200 bytes=4798 protocol=https 2022-02-24T04:49:27.879724+00:00 app[web.1]: I, [2022-02-24T04:49:27.879640 #18] INFO -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] Started POST "/comments" for 124.110.129.63 at 2022-02-24 04:49:27 +0000 2022-02-24T04:49:27.880675+00:00 app[web.1]: I, [2022-02-24T04:49:27.880618 #18] INFO -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] Processing by CommentsController#create as HTML 2022-02-24T04:49:27.880724+00:00 app[web.1]: I, [2022-02-24T04:49:27.880694 #18] INFO -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] Parameters: {"utf8"=>"✓", "authenticity_token"=>"jUDy+JZzZqIEoGhjw7Kco9mOeQhnTlXHNLcTb/zbi/ZKpctS8wS5vxx3P52x6g8qdHT/2fs1zADgo0/rdXhyOg==", "comment"=>{"board_id"=>"74", "comment"=>"ada"}, "commit"=>"送信"} 2022-02-24T04:49:27.891938+00:00 app[web.1]: D, [2022-02-24T04:49:27.891818 #18] DEBUG -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] User Load (2.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 14 LIMIT 1 2022-02-24T04:49:27.892520+00:00 app[web.1]: D, [2022-02-24T04:49:27.892474 #18] DEBUG -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] CACHE User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 14 LIMIT 1 [["id", 14], ["LIMIT", 1]] 2022-02-24T04:49:27.893262+00:00 app[web.1]: I, [2022-02-24T04:49:27.893220 #18] INFO -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] Completed 500 Internal Server Error in 12ms (ActiveRecord: 2.5ms) 2022-02-24T04:49:27.893854+00:00 app[web.1]: F, [2022-02-24T04:49:27.893810 #18] FATAL -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] 2022-02-24T04:49:27.893980+00:00 app[web.1]: F, [2022-02-24T04:49:27.893945 #18] FATAL -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] NoMethodError (undefined method `Comment' for #<User:0x0000563d2ca7e6c0>): 2022-02-24T04:49:27.894039+00:00 app[web.1]: F, [2022-02-24T04:49:27.893982 #18] FATAL -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] 2022-02-24T04:49:27.894085+00:00 app[web.1]: F, [2022-02-24T04:49:27.894048 #18] FATAL -- : [404b23d4-9ff4-4a94-a86f-2b3c26c57e49] app/controllers/comments_controller.rb:5:in `create' 2022-02-24T04:49:27.895986+00:00 heroku[router]: at=info method=POST path="/comments" host=rails-docker-portfolio.herokuapp.com request_id=404b23d4-9ff4-4a94-a86f-2b3c26c57e49 fwd="124.110.129.63" dyno=web.1 connect=0ms service=24ms status=500 bytes=1669 protocol=https

Ruby

1#comment_controller 2 3class CommentsController < ApplicationController 4 def create 5 # comment = Comment.new(comment_params) 6 @user = current_user 7 comment = @user.Comment.new(comment_params) 8 if comment.save 9 flash[:notice] = 'コメントを投稿しました' 10 redirect_to comment.board 11 else 12 redirect_to :back, flash: { 13 comment: comment, 14 error_messages: comment.errors.full_messages 15 } 16 end 17 end 18 19 def destroy 20 comment = Comment.find(params[:id]) 21 comment.delete 22 redirect_to comment.board, flash: {notice: 'コメントが削除されました'} 23 end 24 25 private 26 27 def comment_params 28 params.require(:comment).permit(:board_id, :name, :comment) 29 end 30end

Ruby

1#_comment.html.erb 2<div class="p-comment__item"> 3 <p><%= simple_format(comment.comment) %></p> 4 <div class="p-comment__bottomLine"> 5 <span><%= comment.name %></span> 6 <span><%= comment.created_at.to_s(:datetime_jp) %></span> 7 <span><%= link_to '削除', comment, method: :delete, data: { confirm: '削除してもよろしいですか?' } %></span> 8 </div> 9</div>

Ruby

1#commnet.rb 2 3class Comment < ApplicationRecord 4 belongs_to :board 5 has_many :comments, dependent: :destroy 6 7 validates :name, presence: true, length: {maximum:10} 8 validates :comment, presence: true, length: {maximum:1000} 9end 10

Ruby

1#user.rb 2 3class User < ApplicationRecord 4 has_secure_password 5 has_many :boards, dependent: :destroy 6 has_many :comments, dependent: :destroy 7 8 validates :name, 9 presence: true, 10 uniqueness: true, 11 length: {maximum:16} 12 # format: { 13 # with: /\A[a-z0-9]+\z/, 14 # message: 'は小文字英数字で入力してください' 15 # } 16 validates :password, 17 length: {minimum: 8 } 18 19 def age 20 now = Time.zone.now 21 (now.strftime('%Y%m%d').to_i - birthday.strftime('%Y%m%d').to_i) / 10000 22 end 23end

Ruby

1#board.rb 2class Board < ApplicationRecord 3 has_many :comments, dependent: :delete_all 4 has_many :board_tag_relations, dependent: :delete_all 5 has_many :tags, through: :board_tag_relations 6 has_one_attached :image 7 belongs_to :user 8 9 validates :name, presence: true, length: { maximum: 10 } 10 validates :title, presence: true, length: { maximum: 30 } 11 validates :body, presence: true, length: { maximum: 1000 } 12 13 scope :created_today, -> { where(created_at: Time.zone.now.all_day) } # 今日 14 scope :created_last_month, -> { where(created_at: Time.zone.now.prev_month.all_day) } # 1ヶ月前の投稿 15 scope :created_month, -> { where(created_at: Time.zone.now.all_month) } # 今月の投稿 16 17 validates :image, content_type: { in: %w[image/jpeg image/gif image/png], 18 message: "must be a valid image format" }, 19 size: { less_than: 5.megabytes, 20 message: "should be less than 5MB" } 21 22 # 表示用のリサイズ済み画像を返す 23 def display_image 24 image.variant(resize_to_limit: [500, 500]) 25 end 26end

Ruby

1#UsersController.rb 2class UsersController < ApplicationController 3 def new 4 @user = User.new(flash[:user]) 5 end 6 7 def create 8 user = User.new(user_params) 9 if user.save 10 session[:user_id] = user.id 11 redirect_to mypage_path 12 else 13 flash[:user] = user 14 flash[:error_messages] = user.errors.full_messages 15 redirect_back fallback_location: 'http://localhost' 16 end 17 end 18 19 def me 20 end 21 22 def edit 23 @user = @current_user 24 end 25 26 def update 27 user = @current_user 28 if user.update(user_params) 29 session[:user_id] = user.id 30 redirect_to mypage_path 31 else 32 flash[:error_messages] = user.errors.full_messages 33 end 34 end 35 36 private 37 38 def user_params 39 params.require(:user).permit(:name, :password, :password_confirmation, :faculty, :profile) 40 end 41end

参考記事
https://qiita.com/japwork/items/b2a7e61379c88a5e60c8
https://study-diary.hatenadiary.jp/entry/2020/08/11/231101

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

comment = @user.Comment.new(comment_params)

comment = @user.comments.build(comment_params)
のような気がします。
これでだめだったら、MODELのcode 載せて

投稿2022/02/24 07:24

winterboum

総合スコア23329

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Shmupeiii

2022/02/24 12:39

回答ありがとうございます。 変更したところ以下のエラーが出ました。 2022-02-24T12:39:04.509725+00:00 app[web.1]: F, [2022-02-24T12:39:04.509651 #18] FATAL -- : [fdd5ce80-4281-4da1-bbb7-c8aa7297b7c5] 2022-02-24T12:39:04.509795+00:00 app[web.1]: F, [2022-02-24T12:39:04.509761 #18] FATAL -- : [fdd5ce80-4281-4da1-bbb7-c8aa7297b7c5] ActiveModel::UnknownAttributeError (unknown attribute 'user_id' for Comment.): 2022-02-24T12:39:04.509857+00:00 app[web.1]: F, [2022-02-24T12:39:04.509828 #18] FATAL -- : [fdd5ce80-4281-4da1-bbb7-c8aa7297b7c5] 2022-02-24T12:39:04.509920+00:00 app[web.1]: F, [2022-02-24T12:39:04.509874 #18] FATAL -- : [fdd5ce80-4281-4da1-bbb7-c8aa7297b7c5] app/controllers/comments_controller.rb:5:in `create' またmodelのコードも載せました。よろしくお願いします。
winterboum

2022/02/24 13:24

class Comment < ApplicationRecord の has_many :comments, dependent: :destroy はおかしいでしょう。 belongs_to user では? それと Comment に user_id がないですね
Shmupeiii

2022/02/24 13:57

回答ありがとうございます。 Comment に user_idを追加するには、add_columnなどでcommentにuser_idを足すという感じで合っているでしょうか。よろしくお願いします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問