create_attribute before save in Rails 3.1 doesn't set self.attribute_id
Old code, working in Rails 3.0:
belongs_to :primary_stream
before_save :autocreate_primary_stream, :if=>lambda {|a| a.primary_stream.nil?}
def autocreate_primary_stream
self.create_primary_stream()
end
In Rails 3.1:
self.primary_stream
is populated, and self.primary_stream_id
is nil. When the record is saved, the primary_stream_id is saved as nil to the database.
I've had to do this, to get the behaviour I would expect:
belongs_to :primary_stream
before_save :autocreate_primary_stream, :if=>lambda {|a| a.primary_stream.nil?}
def autocreate_primary_stream
self.create_primary_stream()
self.primary_stream_id = primary_stream.id
end
Has something changed, or have I done something 开发者_StackOverflow社区very silly?
It seems like there may be a bug in the way Rails handles association-creation in callbacks, introduced in 3.1. As far as I can tell, assigning a belongs-to association in before_save won't assign the foreign key to the owner model.
However, the autosaving-association stuff in 3.1 gives a cleaner way of achieving this -
belongs_to :primary_stream
before_validation :autocreate_primary_stream, :if=>lambda {|a| a.primary_stream.nil?}
def autocreate_primary_stream
self.build_primary_stream()
end
and the primary stream will be auto-saved along with the owner record.
https://github.com/rails/rails/issues/1594 was somewhat relevant.
精彩评论