Ruby
1class Message < ApplicationRecord 2 belongs_to :message_room 3 validates :message_room_id, presence: true 4end
Ruby
1class MessagesController < ApplicationController 2 def create_bundle_scout 3 # メッセージの送信先 4 message_destinations = [18, 35, 289] 5 # メッセージの送信先分のmessage_roomを作成 6 message_destinations.each do |message_destination| 7 message = Message.create() 8 message.destination = message_destination 9 message.body = 'スカウトします!' 10 message_room = MessageRoom.create() 11 message_room.type = 'scout' 12 message_room.messages << message 13 end 14 end 15end
説明の都合上、あえてこのような書き方をさせていただいています。
上記ソースコードでDBに保存されている結果は以下の通りでした。
messagesテーブル
id: 1, message_room_id: 1, destination: 18, body: 'スカウトします!'
id: 2, message_room_id: 2, destination: 35, body: 'スカウトします!'
id: 3, message_room_id: 3, destination: 289, body: 'スカウトします!'
message_roomsテーブル
id: 1, type: 'scout'
id: 2, type: 'scout'
id: 3, type: 'scout'
DBに保存されるタイミングをpry-byebugで確認したところ、message_roomは「message_room = MessageRoom.create()」の時点でDBに保存されていましたが、messageは「message_room.messages << message」の時点で保存されていました。createされた時点で保存されるものだと思っていたのですが、「message_room.messages << message」で保存が実行されるのは、どういう仕組みになっているのでしょうか?
不足している情報があれば教えていただければ幸いです。
お手数をおかけしますが、ご回答のほどよろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/29 01:39 編集