rails: has_one through triggering autosave by default

I found the strangest issue by activerecord (3.2.12, not sure how that works in 4). Basically I have the following set this way:

class Bing < ActiveRecord::Base
  belongs_to :bang
  has_one :bong, :through => :bang
end

All is well, until I persist an instance of Bing. If I keep updating it, the bong association is also saved, or autosaved. Only after I explicitly set a flag :autosave => false on the association it stopped. So, the has_one through association is autosavable by default(!), which looks like a bug to me.

I went so far as debugging it all the way to a method in autosave_association called save_has_one_association, where the option[:autosave] is nil. And nil != false (line 390). I don’t know if that is the reason and autosave should be false by default instead of nil. Maybe you can tell me.

I didn’t test it with has_many through relations.

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 23 (6 by maintainers)

Commits related to this issue

Most upvoted comments

I’ve been hitting this issue as well. Although I was not able to fix the issue by setting autosave: false on the belongs_to and has_one associations because I’m also using accepts_nested_attributes_for which sets the autosave value automatically.

Amazingly I found a solution that works. I added the foreign_key value the belongs_to side of the association. Now I can save the model with the has_one in it without triggering a double save after autosaving the model with the belongs_to in it.

In the end, just for good measure, I added the foreign_key setting to both sides of the association.

We encountered this in Rails 4.1.5 today. We had an after_commit callback on an association that would get triggered and we couldn’t figure out why… eventually we figured out it was only getting triggered when we’d load the association on the model before saving. setting autosave: false fixes this, but it was definitely unexpected.

Well, this goes against what is happening in every other association type. And this is what’s troubling to me. This is not a question of what it makes more sense or not, but if with plain has_many, belongs_to and has_one the association is not autosaved, then it shouldn’t be for the :through variants as well… Unless there is a specific good reason and I’m not getting it.