【问题标题】:Rails remove has_one without saveRails 删除 has_one 而不保存
【发布时间】:2016-05-17 16:56:45
【问题描述】:

如何删除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.

我已经在网上搜索了一段时间,但没有找到一个好的答案。

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    您不能将bar 分配为nil,因为它需要外键

    尝试:

    foo.bar.destroy
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      相关资源
      最近更新 更多