Ruby on Rails 5设置has_one child to nil在控制台中失败

问题描述 投票:1回答:1

我目前正在研究关于Lynda的Ruby on Rails Essentials 5培训课程,在关于一对一关联的部分,我创建了一个“主题”,其中包含“Page”。每个模型如下所示:

class Subject < ApplicationRecord

    has_one :page

    scope :visible, lambda {where(:visible => true)}
    scope :invisible, lambda {where(:visible => false)}
    scope :sorted, lambda {order("position ASC")}
    scope :newest_first, lambda {order("created_at DESC")}
    scope :search, lambda {|query| where(["name LIKE ?", "%#{query}%"])}

end

/////

class Page < ApplicationRecord

    belongs_to :subject

end

在db中,我有一个我通过id找到并保存到变量的现有Subject。然后我创建一个新的Page对象(但不保存它),最后,我通过subject.page = page来坚持它。问题是,当我尝试使用subject.page = nil删除关联时,我最终得到以下错误:

irb(main):004:0> subject.page = nil
   (0.3ms)  BEGIN
   (0.2ms)  ROLLBACK
ActiveRecord::RecordNotSaved: Failed to remove the existing associated 
page. The record failed to save after its foreign key was set to nil.
    from (irb):4

我相信页面记录的预期行为是将其外键重新分配为NULL。此行为反映在我正在使用的教程中,以及有关该主题的其他帖子中。我在这里错过了什么?

ruby-on-rails ruby
1个回答
1
投票

从rails 5开始,belongs_to关联的行为已经改变。它检查相关记录是否仍然存在,如果不存在 - 抛出错误。

如果你想保持页面对象没有关联,你应该添加belongs_to:subject,optional:true

© www.soinside.com 2019 - 2024. All rights reserved.