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

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

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

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

Ruby on Rails

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

Q&A

解決済

2回答

1229閲覧

Railsのコメント機能がデータベースへ格納されていない

退会済みユーザー

退会済みユーザー

総合スコア0

Ruby

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

Ruby on Rails

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

0グッド

0クリップ

投稿2019/09/04 18:47

前提・実現したいこと

Railsでのコメント機能を実装したい

発生している問題・エラーメッセージ

現在、Railsでコメント機能を追加したいのですが、コントローラー、ビュー自体は問題なく作動するのですが、コメントがデータベースへ格納されていおらず困っています。

エラーメッセージ

該当のソースコード

ルート Rails.application.routes.draw do devise_for :users root 'tweets#index' resources :tweets do resources :comments, only: [:create] end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end Userモデル class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :tweets,dependent: :destroy has_many :comments, dependent: :destroy end Tweetモデル class Tweet < ApplicationRecord mount_uploader :picture, PictureUploader validates :description, :picture, presence: true belongs_to :user has_many :comments, dependent: :destroy end Commentモデル class Comment < ApplicationRecord belongs_to :user belongs_to :tweet validates :text, presence: true end Tweetsコントローラー class TweetsController < ApplicationController before_action :authenticate_user!, except: [:index] def index @tweets=Tweet.all end def new @tweet=Tweet.new end def show @tweet=Tweet.find_by(id: params[:id]) @comments=@tweet.comments @comment=Comment.new end def create @tweet=current_user.tweets.new(tweet_params) @tweet.save flash[:notice] = "投稿しました" redirect_to root_path end def edit @tweet=Tweet.find_by(id: params[:id]) end def update @tweet=Tweet.find_by(id: params[:id]) @tweet.update(tweet_params) if @tweet.save flash[:notice] = "編集しました" redirect_to root_path else flash[:alert]="画像投稿は必須です。" redirect_to new_tweet_path end end def destroy @tweet=Tweet.find_by(id: params[:id]) @tweet.destroy flash[:notice] = "削除しました" redirect_to root_path end private def tweet_params params.require(:tweet).permit(:description, :picture, :user_id) end end Commentsコントローラー class CommentsController < ApplicationController def create @tweet=Tweet.find_by(id: params[:id]) @comment=Comment.new(comment_params) @comment.user_id=current_user.id @comment.tweet_id=@tweet @comment.save redirect_to root_path end private def comment_params params.require(:comment).permit(:user_id, :tweet_id, :text) end end show.html.erb <div class="container" > <%= @tweet.user.name %> </br><%= @tweet.description %></br> <%= image_tag (@tweet.picture_url) %></br> <% @comments.each do |c| %> <%= c.user.name %> <%= c.text %> <% end %> <% if user_signed_in? %> <%=form_for [@tweet, @comment] do |f| %> <%= f.text_field :text %> <%= f.submit "コメントする" %> <% end %> <% end %> <%= link_to "戻る", root_path %> </div>

試したこと

ここに問題に対して試したことを記載してください。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

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

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

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

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

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

guest

回答2

0

@comment.tweet_id=@tweet

@comment.tweet=@tweet

で解決しました。

投稿2019/09/12 09:20

退会済みユーザー

退会済みユーザー

総合スコア0

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

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

0

ベストアンサー

Commentsコントローラー

1class CommentsController < ApplicationController 2 3def create 4 @tweet=Tweet.find_by(id: params[:id]) 5 @comment=Comment.new(comment_params) 6 @comment.user_id=current_user.id 7 @comment.tweet_id=@tweet # @tweet ではなく、 @tweet.id ? 8 if @comment.save # save は true/false で失敗を返すので、エラーは表示する 9 flash[:notice] = "投稿しました" 10 else 11 Rails.logger.error @comment.errors.full_messages.join('') 12 flash[:error] = "投稿できませんでした" 13 end 14 redirect_to root_path 15end

tweet_id に 設定できてなさそうですが、まずはエラーを表示させる事が大事かと思います。

投稿2019/09/04 20:22

編集2019/09/04 20:23
unhappychoice

総合スコア1531

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

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

退会済みユーザー

退会済みユーザー

2019/09/04 21:33 編集

4行目の @tweet=Tweet.find_by(id: params[:id])において、 SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`id` IS NULL LIMIT 1 と表示されidがNULLの扱いになり、エラーになりました。 全文こちらです Started POST "/tweets/81/comments" for 114.134.219.248 at 2019-09-04 21:31:38 +0000 Cannot render console from 114.134.219.248! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 Processing by CommentsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"NuXyfwCWgbaH+DIgB/Ovb5jYeTfcgLFUa/u670JcrAnlj4lkBfKGs5wo1mX0sJRaKVeowY28Jo5ut3Fo9d7I5g==", "comment"=>{"text"=>"aaaa"}, "commit"=>"コメントする", "tweet_id"=>"81"} User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 ORDER BY `users`.`id` ASC LIMIT 1 ↳ /usr/local/rvm/gems/ruby-2.5.1/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98 Tweet Load (0.1ms) SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`id` IS NULL LIMIT 1 ↳ app/controllers/comments_controller.rb:4 (0.1ms) BEGIN ↳ app/controllers/comments_controller.rb:8 User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 LIMIT 1 ↳ app/controllers/comments_controller.rb:8 (0.1ms) ROLLBACK ↳ app/controllers/comments_controller.rb:8 Tweetを入力してください Redirected to https://d4f2f975039e4257b3fa9927d2035d95.vfs.cloud9.ap-southeast-1.amazonaws.com/ Completed 302 Found in 11ms (ActiveRecord: 0.8ms) 念のため@tweet.idでやると undefined method `id' for nil:NilClass というエラー文が表示されました
unhappychoice

2019/09/04 22:18

なるほど、 bundle exec rake routes の結果を見ないといけないですが、 params[:id] ではなく params[:tweet_id] ではないですか?
退会済みユーザー

退会済みユーザー

2019/09/10 16:34 編集

返事気が付かなくて遅くなりました。申し訳ございません。 params[:tweet_id]に変えたところNULLにはならなくなりましたが、依然データベースには格納されないです。 Started POST "/tweets/89/comments" for 114.134.219.248 at 2019-09-10 16:32:27 +0000 Cannot render console from 114.134.219.248! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 Processing by CommentsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"7c4tAC0/KgQqLFz1pTbnr+vMpyL1rkWh1C+Fl3QaVYY+pFYbKFstATH8uLBWddyaWkN21KSS0nvRY04Qw5gxaQ==", "comment"=>{"text"=>"asaa"}, "commit"=>"コメントする", "tweet_id"=>"89"} User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 ORDER BY `users`.`id` ASC LIMIT 1 ↳ /usr/local/rvm/gems/ruby-2.5.1/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98 Tweet Load (0.2ms) SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`id` = 89 LIMIT 1 ↳ app/controllers/comments_controller.rb:4 (0.1ms) BEGIN ↳ app/controllers/comments_controller.rb:8 User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 LIMIT 1 ↳ app/controllers/comments_controller.rb:8 (0.1ms) ROLLBACK ↳ app/controllers/comments_controller.rb:8 Tweetを入力してください Redirected to https://d4f2f975039e4257b3fa9927d2035d95.vfs.cloud9.ap-southeast-1.amazonaws.com/ Completed 302 Found in 12ms (ActiveRecord: 0.8ms)
perpouh

2019/09/12 06:26

@comment.tweet_id=@tweet @tweetの中身ってモデルオブジェクトじゃないですか? @comment.tweet = @tweetか@comment.tweet_id = @tweet.idとしてみてはどうでしょう?
退会済みユーザー

退会済みユーザー

2019/09/12 09:17

@comment.tweet = @tweetで解決しました。ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.49%

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

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

質問する

関連した質問