【问题标题】:Field_for in nested attributes is giving problem嵌套属性中的 Field_for 出现问题
【发布时间】:2011-09-21 20:10:32
【问题描述】:

我对编程和 Ruby on Rails 都很陌生。我只是在尝试使用示例 2 级深度嵌套。当我按照 Ryan 的 Scraps (http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes) 进行 1 级深度嵌套时,一切都很好,但是当我扩展为 2 级深度,具有以下要求: 而不是一次创建父母,孩子和孙子,我想先创建父母然后孩子和孙子一起。我的代码是

我的模特:

class Parent < ActiveRecord::Base
has_many :children
has_many :grand_children
accepts_nested_attributes_for :children, :allow_destroy => true
accepts_nested_attributes_for :grand_children, :allow_destroy => true
end

class Child < ActiveRecord::Base
belongs_to :parent
has_many :grand_children
accepts_nested_attributes_for :grand_children
end

class GrandChild < ActiveRecord::Base
belongs_to :parent
belongs_to :child
end

我的孩子控制器 - 新方法:

    def new
@parent = Parent.find(params[:parent_id])
child = Child.new
child.grand_children.build
respond_to do |format|
format.html # new.html.erb
format.xml  { render :xml => @child }
end
end

我的孩子_form模板是

<%= form_for([@parent, @parent.children.build]) do |form|  %>  
<div>
<%= form.label :name %><br />
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :sex %><br />
<%= form.text_field :sex %>
</div>
<div>
<%= form.fields_for :grand_children do |grand_child_form| %>
<%= render :partial => "grand_children/form", :locals => { :form => grand_child_form}     %>
<% end %>
</div>
<% end %>

在这里我没有收到任何错误,但是当我选择新孩子时,grand_child 没有出现,

 <%= form.fields_for :grand_children do |grand_child_form| %>
  <%= render :partial => "grand_children/form", :locals => { :form => grand_child_form} %>
<% end %>

根本没有得到反映。

提前致谢

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    大家好,我通过反复试验得到了解决方案,

    儿童表单模板是

    <div>
    <%= form.fields_for :grandchildren, @grand_child do |grand_child_form| %>
    <%= render :partial => "grandchildren/form", :locals => { :form => grand_child_form} %>
    <% end %>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2016-03-23
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多