###前提・実現したいこと
Rails4
PostgreSQL
現在、railsでdeviseを使用しログイン機能を実装し、ログインユーザーがユーザー同士、個別にメッセージのやり取りができるようにしました。
具体的なテーブル構成は
usersテーブル(ユーザ情報を格納する) conversationsテーブル(会話情報を格納する) messagesテーブル(会話の個々のメッセージを格納する)
このようにしました。
現在のコードではメッセージをやり取りしたユーザーが退会すると外部キー制約によりデータが削除できないというエラーが発生してしまいます。
どこを修正すればいいかアドバイスをお願いします。
###発生している問題・エラーメッセージ
メッセージのやり取りをしたユーザーが退会(ユーザーの削除)しようとすると以下のようなエラーが出てユーザーを削除することができません。
PG::ForeignKeyViolation at /users ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_273a25a7a6" on table "messages"
###該当のソースコード
message.rb
ruby
1class Message < ActiveRecord::Base 2 belongs_to :conversation 3 belongs_to :user, dependent: :destroy 4 5 validates_presence_of :body, :conversation_id, :user_id 6 def message_time 7 created_at.try(:strftime,"%m/%d %R") 8 end 9end
conversation.rb
ruby
1class Conversation < ActiveRecord::Base 2 belongs_to :sender, foreign_key: :sender_id, class_name: 'User' 3 belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User' 4 has_many :messages, dependent: :destroy 5 validates_uniqueness_of :sender_id, scope: :recipient_id 6 scope :between, -> (sender_id,recipient_id) do 7 where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id) 8 end 9 10 def target_user(current_user) 11 if sender_id == current_user.id 12 User.find(recipient_id) 13 elsif recipient_id == current_user.id 14 User.find(sender_id) 15 end 16 end 17end
今はこのようにコードを書いています。
他に必要なコードがあれば記載しますので、ご教授よろしくお願いします。
###補足・追記
Messagesテーブルのマイグレーションファイル
class CreateMessages < ActiveRecord::Migration def change create_table :messages do |t| t.text :body t.references :conversation, index: true, foreign_key: true t.references :user, index: true, foreign_key: true t.boolean :read, default: false t.timestamps null: false end end end
Conversationsテーブルのマイグレーションファイル
class CreateConversations < ActiveRecord::Migration def change create_table :conversations do |t| t.integer :sender_id t.integer :recipient_id t.timestamps null: false end end end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/06/18 00:21