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

那年仲夏 提交于 2019-11-28 22:11:26

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!