简体   繁体   中英

How do I create a parent record from the child when the parent doesn't exist?

I've trying to model books, chapters, and notes.

I have the following:

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

I can create Books and notes just fine.

What I want to do when creating a new Note is either create a new Chapter or assign an existing one to a note . Said another way: I'm trying to create a parent from the child before the parent even exists, or assigning an exising parent to the child.

This is the kind of functionality that's provided by gems such as acts_as_taggable_on . I've tried using nested forms, but just couldn't get it near to what I wanted. I'm wondering if my architecture is even correct for this type of use? Any guidance you could provide would be much appreciated.

In your create method in your NotesController you could do something like

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

The method find_or_create_by I think is what you needed here. If that method is depreciated in your rails version, tryfirst_or_create , like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM