首页 > 解决方案 > 当父级不存在时,如何从子级创建父记录?

问题描述

我试图为书籍、章节和笔记建模。

我有以下内容:

class Book < ApplicationRecord
    has_many :chapters
    has_many :notes
end
class Chapter < ApplicationRecord
    belongs_to :book
    has_many :notes
end
class Note < ApplicationRecord
    belongs_to :chapter
end

我可以很好地创建书籍和笔记。

创建新文件时我想做的Note是创建新Chapter文件或将现有文件分配给note. 换一种说法:我试图在父级甚至存在之前从子级创建父级,或者将现有父级分配给子级。

这是由 gem 提供的功能,例如acts_as_taggable_on. 我尝试过使用嵌套表单,但无法让它接近我想要的。我想知道我的架构是否适合这种类型的使用?您可以提供的任何指导将不胜感激。

标签: ruby-on-rails

解决方案


在 NotesController 的 create 方法中,您可以执行类似的操作

parent_chapter = Chapter.find_or_create_by(name: 'How To Program')
# parent_chapter is now either the existing chapter by that name or a new one
new_note = Note.new(params[:note])
new_note.chapter = parent_chapter # or new_note.chapter_id = parent_chapter.id
new_note.save

我认为find_or_create_by方法是您在这里需要的。如果该方法在您的 rails 版本中被贬值,请尝试first_or_create,像这样

parent_chapter = Chapter.where(name: 'How To Program').first_or_create

推荐阅读