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 这正是我想要完成的,但我仍然是Rails的新手,并想知道是否有人可以向我展示所需的表格和控制器样本,以便能够为此设置创建记录? 我能够创建第一部分(文档有很多部分),但我一直在搞清楚如何实现部分有很多段落以及如何能够在三者之间进行引用.我已经搜索了上面的例子的高低,并且真的很感激新的,创建,更新动作和相应表单的示例代码. 非常感谢提前! 更新: 我有我的3个模型(用户,出版物,问题),它们在每个自己的视图和控制器中分开.目标是拥有一个控制面板,登录用户可以点击链接到: a)添加/编辑/删除与个人用户相关的出版物 b)添加/编辑/删除与各个出版物相关的问题 因此,我有3个单独的表格(用户,出版物和问题). 在我的publications_controller中,我设法: @publication = current_user.publications.build(params[:publication]) 将用户和出版物链接在一起并使用发布模型中的正确user_id字段(未在attr_accessible中列出)填充,以便工作得很好. 现在我的挑战是在出版物上添加问题,这就是我昙花一现的地方.我有一个菜单,我可以在其中添加问题,但我不希望表单中的publication_id字段,也不在模型中的attr_accessible中.我想通过用户使用所选出版物创建一个问题. 对不起,如果我不能解释清楚这对我来说还是一个新鲜事,也可能也是为什么我在搜索正确的术语时遇到麻烦. 解决方法
希望对你有帮助:
楷模: 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 控制器: class DocumentsController < ApplicationController def new @document = Document.new @document.sections.build @document.paragraphs.build end end 浏览次数: 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 谢谢 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |