I have a simple rails webservice that exposes a JSON API that allows clients to POST a new record. When the POST is processed, it first creates the referenced record, but also updates some related records at the same time.
@foo = Foo.new(foo_params)
if @foo.save
related_list = Foo.where(:some_id => foo_params[:list])
related_list.each do |related|
# <figure out some stuff here>
related.update_attributes(stuff)
end
# debug spew
@test = Foo.find(a_related_record_id)
puts @test.as_json
format.json { render json: @foo.as_json }
end
I recognize this is a bad two-phase commit pattern, and it’s abusive of the typical REST model, but I inherited this code. I’m going to fix it eventually; this is all part of the “fixing” plan in stages.
This code works perfectly on a local test box. When deployed to Heroku, I put in debug spew that shows the model apparently being updated after update_attributes is called. However, somehow, the model isn’t actually updated. When I check on the “related” records afterwards using a webpage, none of them have been updated with the “stuff” changes. I’m quite baffled by this since the debug spew appears to show the record being updated. Any insights?
Update
One thing I just noticed as I went back through my debug spew is that the updated_at datetime never changes, even though the field in the record appears to have. You can see from the lines below that the call was made around 8:04:15 UTC. Also, I verified that update_attributes was returning true, so there was no error as far as I could tell.
Before update_attributes is called:
←[36m2012-09-20T08:04:15+00:00 app[web.1]:←[0m { “created_at”=>Thu, 20 Sep 2012 00:43:45 UTC +00:00, “somefield”=>””, “id”=>2, “updated_at”=>Thu, 20 Sep 2012 06:22:07 UTC +00:00}
After update_attributes is called:
←[36m2012-09-20T08:04:15+00:00 app[web.1]:←[0m { “created_at”=>Thu, 20 Sep 2012 00:43:45 UTC +00:00, “somefield”=>”10000848364”, “id”=>2, “updated_at”=>Thu, 20 Sep 2012 06:22:07 UTC +00:00}
After much painstaking research, I managed to figure out the source of the issue, and the fix, but I’m not clear why this is happening. Still, it’s unblocking me for now, and that suffices.
In the code above, within the
block. There was code that I abstracted out in the original question since I didn’t think it was pertinent. Turns out it was. Specifically, there was a line where I was doing a string concatenation:
This one line, for some reason, caused
not to save to the database. This was 100% reproducible (trust me, I tested it about 10 times to be sure). The fix was simple:
That, seriously, fixed the problem. I did not debug deep into the guts of the in-place concatenation within ruby to determine the root cause, but if someone else ever encounters this problem, well, now you know.