我有一个可以很好地创建的表列表。然后,我希望能够通过单击父级上的编辑(转到 edit.html.erb)然后单击“新建子级”来创建子表。父子表的关系是has_and_belongs_to_many。
<%= button_to 'New Child', new_parent_child_path([@parent, @parent.children.build]), :method => :get %>
这是新子表单的链接,产生以下错误:
'undefined method `children' for nil:NilClass'
服务器日志给了我以下信息:
Started GET "/parents/1//children/new" for blah at blah
Processing by ChildrenController#new as HTML
Parameters: {"parent_id"=>"1"}
Rendered children/_form.html.erb (1.3ms)
Rendered children/new.html.erb within layouts/application (1.9ms)
Completed 500 Internal Server Error in 4ms
ActionView::Template::Error (undefined method `children' for nil:NilClass):
1: <%= form_for ([@parent, @parent.children.build]) do |f| %>
2:
3: <div class = "field">
4: <%= f.label :Child_name %><br/>
app/views/children /_form.html.erb:1:in`_app_views_children__form_html_erb__2140243687_70034946643120'
app/views/children/new.html.erb:3:in `_app_views_children_new_html_erb__655166082_70034947829100'
在子 new.html.erb 中呈现的 _form.html.erb 如下:
<%= form_for ([@parent, @parent.children.build]) do |f| %>
<div class = "field">
<%= f.label :Child_name %><br/>
<%= f.text_field :ChildName %>
</div>
<div class = "field">
<%= f.label :Child_email_address %><br/>
<%= f.text_field :ChildEmail %>
</div>
<div class = "actions">
<%= f.submit %>
</div>
<% end %>
(注意:这些表实际上并不称为 parent 和 child,我只是出于保密的原因使用了这些名称。另外,请不要建议我使用 has_many through,我不感兴趣。)
编辑#1:来自“ChildrenController”的代码
def new
@child = Child.new
end
def create
@parent = Parent.find(params [:parent_id])
@scout = @parent.children.build(params[:child])
redirect_to parent_path(@parent)
end