Ruby on rails RubyonRails5设置在控制台中有一个子项为零失败
我目前正在学习关于Lynda的Ruby on Rails Essentials 5培训课程,在关于一对一关联的部分中,我创建了一个包含一个“页面”的“主题”。每个模型如下所示:Ruby on rails RubyonRails5设置在控制台中有一个子项为零失败,ruby-on-rails,ruby,Ruby On Rails,Ruby,我目前正在学习关于Lynda的Ruby on Rails Essentials 5培训课程,在关于一对一关联的部分中,我创建了一个包含一个“页面”的“主题”。每个模型如下所示: class Subject < ApplicationRecord has_one :page scope :visible, lambda {where(:visible => true)} scope :invisible, lambda {where(:visible =&g
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
我相信预期的行为是页面记录的外键被重新分配为NULL。这种行为反映在我正在使用的教程中,以及关于这个主题的其他帖子中。我在这里遗漏了什么?自从rails 5以来,属于关联的行为已经改变。 它检查相关记录是否存在,如果不存在,则抛出错误 如果要保留没有关联的页面对象,应添加 属于:主题,可选:true可能是重复的:请参阅:
class Page < ApplicationRecord
belongs_to :subject
end
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