ruby-on-rails - 当父级不存在时,如何从子级创建父记录?
问题描述
我试图为书籍、章节和笔记建模。
我有以下内容:
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
. 我尝试过使用嵌套表单,但无法让它接近我想要的。我想知道我的架构是否适合这种类型的使用?您可以提供的任何指导将不胜感激。
解决方案
在 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
推荐阅读
- wordpress - 如何在 localhost 中使用 xampp 在 wordpress 上进行协作
- mysql - 使用 Where 条件和旧的更新触发器。数据
- octave - 八度 - 未定义
- javascript - 来自 bootstrap4 的 Tempus dominus
- html - 初始 CSS 过渡不会播放
- android - 当我使用 Android Studio 4.0 时,NotificationCompat 和 NotificationCompat.Style 是否都已过时?
- python - Django 表单:初始字段值不适用于 @staticmethod 与未绑定函数
- python - 更改气泡图中气泡的大小
- format - 在 Octave 中使用 num2str 的奇怪行为
- php - 分页错误 - laravel Method Illuminate\Database\Eloquent\Collection::paginate 不存在