前提
Ruby on Railsで映画のレビューサイトを作っています。
映画のIDを取得して、レビューを投稿しようとしたところ、以下のエラーメッセージが発生しました。
外部キーの制約の問題だと思われますが、同内容のエラーが各種サイトでは見つからず、対応方法が分からなかったため、質問させていただきます。
実現したいこと
- 外部キーの制約の問題を解消し、レビューを投稿できるようにしたい
発生している問題・エラーメッセージ
ActiveRecord::InvalidForeignKey in CommentsController#create SQLite3::ConstraintException: FOREIGN KEY constraint failed: INSERT INTO "comments" ("content", "user_id", "movie_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)
該当のソースコード
エラーと関係していると思われるソースコードや必要情報を記載いたしました。
1. comments_controller
2. schema
3. 外部キーの制約に関するマイグレーション
4. commentモデル
5. userモデル
6. movieモデル
ーーーーーーーーーーーーーーーーーーーーー
1. comments_controller
class CommentsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] before_action :correct_user, only: :destroy def create puts params @comment = Comment.new() @comment.content = params["comment"][:content] @comment.user_id = current_user.id @comment.movie_id = params["comment"][:movie_id] # @comment = Comment.new(comment_params) # @comment = current_user.comments.build(comment_params) if @comment.save flash[:success] = "Comment created!" redirect_to root_url else @feed_items = [] render 'static_pages/home' end end def destroy @comment.destroy flash[:success] = "Comment deleted" redirect_to request.referrer || root_url end private def comment_params params.require(:comment).permit(:content, :user_id) end def correct_user @comment = current_user.comments.find_by(id: params[:id]) redirect_to root_url if @comment.nil? end end
2. schema
ActiveRecord::Schema.define(version: 20220313085506) do create_table "comments", force: :cascade do |t| t.text "content" t.integer "user_id" t.integer "movie_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["movie_id"], name: "index_comments_on_movie_id" t.index ["user_id", "movie_id", "created_at"], name: "index_comments_on_user_id_and_movie_id_and_created_at" t.index ["user_id"], name: "index_comments_on_user_id" end create_table "movies", force: :cascade do |t| t.string "title" t.string "date" t.string "story" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.string "name" t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "password_digest" t.string "remember_digest" t.boolean "admin", default: false t.string "activation_digest" t.boolean "activated", default: false t.datetime "activated_at" t.string "reset_digest" t.datetime "reset_sent_at" t.index ["email"], name: "index_users_on_email", unique: true end end
3. 外部キーの制約に関するマイグレーション
class CreateComments < ActiveRecord::Migration[5.1] def change create_table :comments do |t| t.text :content t.references :user, foreign_key: true t.references :movie, foreign_key: true t.timestamps end add_index :comments, [:user_id, :movie_id, :created_at] end end
4. commentモデル
class Comment < ApplicationRecord belongs_to :user belongs_to :movie, optional: true default_scope -> { order(created_at: :desc) } validates :user_id, presence: true validates :content, presence: true, length: { maximum: 250} end
5. userモデル
class User < ApplicationRecord has_many :comments, dependent: :destroy has_many :movies, through: :comments attr_accessor :remember_token, :activation_token, :reset_token before_save :downcase_email before_create :create_activation_digest validates :name, presence: true, length: { maximum: 50} VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255}, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 }, allow_nil: true def User.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def User.new_token SecureRandom.urlsafe_base64 end def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end def authenticated?(remember_token) return false if remember_digest.nil? BCrypt::Password.new(remember_digest).is_password?(remember_token) end def forget update_attribute(:remember_digest, nil) end def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end def activate update_columns(activated: true, activated_at: Time.zone.now) end def send_activation_email UserMailer.account_activation(self).deliver_now end def create_reset_digest self.reset_token = User.new_token update_columns(reset_digest: User.digest(reset_token), reset_sent_at: Time.zone.now) end def send_password_reset_email UserMailer.password_reset(self).deliver_now end def password_reset_expired? reset_sent_at < 2.hours.ago end def feed Comment.where("user_id = ?", id) end private def downcase_email self.email.downcase! end def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end
6. movieモデル
class Movie < ApplicationRecord include HTTParty has_many :comments, dependent: :destroy has_many :users, through: :comments default_options.update(verify: false) default_params api_key: '#実際はコードが入っています', language: "ja-JP" format :json def self.search term base_uri 'https://api.themoviedb.org/3/search/movie' get("", query: { query: term}) end def self.details id #base_uri "https://api.themoviedb.org/3/movie/#{id}" get("https://api.themoviedb.org/3/movie/#{id}", query: {} ) end # def self.popular(page=1) # base_uri 'https://api.themoviedb.org/3/movie/popular' # get("", query: { language: 'ja-JP', region: "JP" }) # end end
コメント
初心者であり、至らないところがありましたら、申し訳ございません。
ソースコードに関しましては、必要なものがありましたら、追記いたしますので、教えていただければ幸いです。
何卒宜しくお願い致します。
回答3件
あなたの回答
tips
プレビュー