前提・実現したいこと
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/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。