Rails删除has_one而不保存

时间:2016-05-17 16:56:46

标签: ruby-on-rails activerecord associations

如何通过提交数据库来删除has_one关系?

class Foo
  has_one :bar

  validates :bar, presence: true
end

class Bar
  belongs_to :foo

  validates :foo, presence: true
end

foo = Foo.new
foo.build_bar
foo.save # => success

foo.bar = nil # => Failed to remove the existing associated bar. The record failed to save after its foreign key was set to nil.

我一直在网上搜索,但没有找到一个好的答案。

1 个答案:

答案 0 :(得分:0)

您无法将bar指定为nil,因为它需要外键

尝试:

foo.bar.destroy