The problem is in the model. before_create
callback is called before creating a ConversationUser
. Let's name this created ConversationUser
as CURRENT
. So, before creating the CURRENT
ConversationUser
you loop through recipient ids and create a ConversationUser
for each of them. The ConversationUser
s that you are creating here are not CURRENT
ConversationUser
. CURRENT
ConversationUser
is saved after the callback is executed (after you create other ConversationUser
s). But in this case CURRENT
ConversationUser
doesn't know wich User
it belongs to, because you pass user_id
parameter to ConversationUser
s that you create in before_create
callback, but you do not pass it to CURRENT
ConversationUser
when it is created (when original create!
method is executed).
To solve this problem you can override original create!
method or not use it at all for creating ConversationUser
s by recipient ids. Add a new method to your Conversation
model (for example create_conversation_users
):
Solution
In the controller:
def create
@conv = Conversation.create!
@conversation = @conv.create_conversation_users!(conversation_user_params[:recipient])
end
In the model:
class Conversation
def create_conversation_users!(recipient_ids)
return if recipient_ids.blank?
recipient_ids.each do |recipient_id|
conversation_users.create!(user_id: recipient_id, conversation: self)
end
end
end
You should also update ConversationUser
model:
class ConversationUser < ActiveRecord::Base
validates :user_id, :conversation_id, presence: true
end