老代码,在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在Rails3.1中:填充了self.primary_stream,而self.primary_stream_id为空。保存记录时,primary_stream_id将作为nil保存到数据库。
我不得不这样做,以获得我所期望的行为:
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是有什么改变了,还是我做了什么很愚蠢的事?
发布于 2011-06-23 17:52:22
Rails在3.1中引入的在回调中处理关联创建的方式似乎存在一个bug。据我所知,在before_save中分配一个归属关联不会将外键分配给所有者模型。
然而,3.1中的自动保存关联提供了一种更清晰的方式来实现这一点-
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并且主流将与所有者记录一起被自动保存。
https://github.com/rails/rails/issues/1594在某种程度上是相关的。
https://stackoverflow.com/questions/6443845
复制相似问题