Examples of new, create actions for has_many :through associations (nested)

后端 未结 1 1536

I found this code on http://guides.rubyonrails.org/association_basics.html#the-has_one-through-association:

class Document < ActiveRecord::Base
  has_many         


        
相关标签:
1条回答
  • 2020-12-15 02:45

    Hope this will help you:

    Models:

    class Document < ActiveRecord::Base
        has_many :sections
        has_many :paragraphs, :through => :sections
        accepts_nested_attributes_for :sections, :allow_destroy => true
        accepts_nested_attributes_for :paragraphs, :allow_destroy => true
    end
    
    class Section < ActiveRecord::Base
        belongs_to :document
        has_many :paragraphs
     end
    
    class Paragraph < ActiveRecord::Base
        belongs_to :section
    end
    

    Controllers:

    class DocumentsController < ApplicationController
    
        def new
            @document = Document.new
            @document.sections.build
            @document.paragraphs.build
        end
    end
    

    Views:

    form_for @document do |f|
    
         ----document fields----------
    
         f.fields_for :sections do |s|
            ----sections fields----------
         end
    
         f.fields_for :paragraphs do |s|
              ----paragraphs fields----------
         end
    
    end
    

    Thanks

    0 讨论(0)
提交回复
热议问题