3

旧代码,在 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

在 Rails 3.1 中: self.primary_stream已填充,并且self.primary_stream_id为 nil。保存记录时,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

有什么改变,还是我做了一些非常愚蠢的事情?

4

1 回答 1

2

似乎 Rails 在 3.1 中引入的回调中处理关联创建的方式可能存在错误。据我所知,在 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有点相关。

于 2011-06-23T09:52:21.940 回答