has_many的new,create动作示例:通过关联(嵌套)

Nic*_*tin 1 ruby-on-rails has-many

我在http://guides.rubyonrails.org/association_basics.html#the-has_one-through-association上找到了这段代码:

class Document < ActiveRecord::Base
  has_many :sections
  has_many :paragraphs, :through => :sections
end

class Section < ActiveRecord::Base
  belongs_to :document
  has_many :paragraphs
end

class Paragraph < ActiveRecord::Base
  belongs_to :section
end
Run Code Online (Sandbox Code Playgroud)

这正是我想要完成的,但我仍然是Rails的新手,并想知道是否有人可以向我展示所需的表格和控制器样本,以便能够为此设置创建记录?

我能够创建第一部分(文档有很多部分),但我一直在搞清楚如何实现部分有很多段落以及如何能够在三者之间进行引用.我已经搜索了上面的例子的高低,并且真的很感激新的,创建,更新动作和相应表格的示例代码.

非常感谢提前!

更新:我非常感谢您对此的帮助,并感谢您的快速回复.也许我需要澄清一点.

我有我的3个模型(用户,出版物,问题),它们在每个自己的视图和控制器中分开.目标是拥有一个控制面板,登录用户可以点击链接到:

a)添加/编辑/删除与个人用户相关的出版物

b)添加/编辑/删除与各个出版物相关的问题

因此,我有3个单独的表格(用户,出版物和问题).

在我的publications_controller中,我设法:

@publication = current_user.publications.build(params[:publication])
Run Code Online (Sandbox Code Playgroud)

将用户和出版物链接在一起并使用发布模型中的正确user_id字段(未在attr_accessible中列出)填充,以便工作得很好.

现在我的挑战是在出版物上添加问题,这是我有点短暂的地方.我有一个菜单,我可以添加问题,但我不希望表单中的publication_id字段,也没有在模型中的attr_accessible.我想通过用户使用所选出版物创建问题.

对不起,如果我不能解释清楚这对我来说还是很新的,也可能也是为什么我在搜索正确的术语时遇到了麻烦.

Ank*_*ria 11

希望对你有帮助:

楷模:

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
Run Code Online (Sandbox Code Playgroud)

控制器:

class DocumentsController < ApplicationController

    def new
        @document = Document.new
        @document.sections.build
        @document.paragraphs.build
    end
end
Run Code Online (Sandbox Code Playgroud)

浏览次数:

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
Run Code Online (Sandbox Code Playgroud)

谢谢