Rails ActiveRecord shovel operator (<<) Update doesn't succeed without exception in the log

My data model has Meetings that may have Attachments. My update_meeting API has the following lines (among others):

attachment = Attachment.new(image: params[:attachment], user: current_user)
begin
  attachment.save!
  @meeting.attachments << attachment
  NotificationManager.add_attachment_to_meeting(current_user, @meeting, attachment)
rescue
  puts "Error occured trying to upload attachment: #{attachment.inspect}, #{attachment.errors.inspect}"
end

We experienced a special case where an Attachment got created but is not associated with a meeting in the database. I started to dig into the logs to find out what happened. I can't see any errors, exceptions, rollbacks, anything like that. Particularly these 3 lines are there:

(0.7ms)  BEGIN
SQL (1.0ms)  UPDATE "attachments" SET "updated_at" = $1, "meeting_id" = $2 WHERE "attachments"."id" = $3  [["updated_at", 2018-07-06 13:57:52 UTC], ["meeting_id", 434], ["id", 51]]
(1.3ms)  COMMIT

My assumption (prior to seeing this) would have been that if there is an UPDATE statement followed by a COMMIT without a ROLLBACK or error message or anything in the log that it should have succeeded. But apparently not.

Does anybody have any pointers where this could have gone wrong? I'm completely out of ideas on where to start looking now. Not sure how to reproduce, not sure what log messages to add to make it easier the next time it happens, not sure...

I'm using Rails 5 and PostgreSQL running on EC2.

1 answer

  • answered 2018-07-12 07:39 Luiz E.

    let the meeting create the attachment

    begin
      attachment = @meeting.attachments.create(image: params[:attachment], user: current_user)
      NotificationManager.add_attachment_to_meeting(current_user, @meeting, attachment)
    rescue
      puts "Error occured trying to upload attachment: #{attachment.inspect}, #{attachment.errors.inspect}"
    end
    

    the meeting should be like an "aggregator" for attachments. attachments should not exist or at least, do not make sense for to them exist without a meeting, so they should be created through the meeting