RubyonRailsでユーザーログインしている方のみがコメントをできる仕組みを作っています。
投稿まではできている(ように見える)のですが、実際に保存がされません。
(エラーメッセージは出ず、すました感じでホーム画面に戻ります汗)
チュートリアル通りに進めているはずなのですが・・・
すみませんが、教えていただけませんでしょうか?
環境:
Ruby on Rails 5.0.0.1
Devise
##該当するソースコード
comment.rb
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 7 validates :content, presence: true, length: { maximum: 2000, minimum: 100 } 8end
▼ comment_controller.rb
ruby
1class commentsController < ApplicationController 2 before_action :signed_in_user 3 before_action :correct_user, only: :destroy 4 5 def create 6 @comment = current_user.comments.build(comment_params) 7 if @comment.save 8 flash[:success] = "コメントが投稿されました!" 9 redirect_to root_path 10 else 11 redirect_to root_path 12 end 13 end 14 15 def show 16 @comment = comment.find(params[:id]) 17 end 18 19 def new 20 @comment = current_user.comments.build if signed_in? 21 end 22 23 def destroy 24 @comment.destroy 25 flash[:success] = "コメントが削除されました" 26 redirect_to request.referrer || root_url 27 end 28 29 def edit 30 end 31 32 def update 33 end 34 35 private 36 37 def comment_params 38 params.require(:comment).permit(:id,:content, :title, :article_id, :user_id) 39 end 40 41 def correct_user 42 @comment = current_user.comments.find_by(id: params[:id]) 43 redirect_to root_url if @comment.nil? 44 end 45end
▼ マイグレーションファイル
ruby
1class CreateComments < ActiveRecord::Migration[5.0] 2 def change 3 create_table :comments do |t| 4 t.text :title 5 t.text :content 6 t.references :user, foreign_key: true 7 t.references :article, foreign_key: true 8 9 t.timestamps 10 end 11 add_index :comments, [:user_id, :article_id, :created_at] 12 end 13end 14
###試してみたこと
modelにparamsを追加してみたのですが、やはり上手くいきませんでした。。
ruby
1 def comment_params 2 params.require(:comment).permit(:id,:content, :title, :article_id, :user_id) 3 end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/06/16 01:48