首先,如果你花时间看这个,我要感谢你。谢谢:)。
所以,我终于想出了如何在顶级资源的_form.html.erb中正确嵌套资源。我的最终项目将从上到下拥有以下嵌套资源:IDFs =>开关=>插孔。目前我通过创建一个新的插孔来解决所有问题...这给了我以下错误:
NoMethodError in Jacks#new
Showing /var/rails/network/app/views/jacks/_form.html.erb where line #1 raised:
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for [@switch, @jack] do |f| %>
2: <% if @jack.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(@jack.errors.count, "error") %> prohibited this jack from being saved:</h2>
我的所有模型都是脚手架,除了要关联的模型,修复路径的控制器和_form.html.erb文件之外,我还没有碰过他们的许多文件。我会发布我认为相关的代码,但是如果有其他任何东西可以帮助我,如果你看到它然后让我知道。
应用程序/控制器/ jacks_controller.rb:
...
def new
@jacks = Jack.new(:switch_id => params[:switch_id])
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @jack }
end
end
...
应用程序/视图/开关/ _form.html.erb:
<%= form_for [@idf, @switch] do |switch_form| %>
<% if @switch.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@switch.errors.count, "error") %> prohibited this switch from being saved:</h2>
<ul>
<% @switch.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= switch_form.label :title %><br />
<%= switch_form.text_field :title %>
</div>
<div class="field">
<%= switch_form.label :model %><br />
<%= switch_form.text_field :model %>
</div>
<% switch_form.fields_for :jacks do |jack_form| %>
<p>
<div class="field">
<%= jack_form.label :port, 'Port:' %>
<%= jack_form.text_field :port %>
</div>
<div class="field">
<%= jack_form.label :jack_number, 'Jack Number:' %>
<%= jack_form.text_field :jack_number %>
</div>
<div class="field">
<%= jack_from.label :room_number, 'Room Number:' %>
<%= jack_form.text_field :room_number %>
</div>
<% unless jack_form.object.new_record? %>
<div>
<%= jack_form.label :_delete, 'Remove:' %>
<%= jack_form.check_box :_delete %>
</div>
<% end %>
<p>
<% end %>
<div class="actions">
<%= switch_form.submit %>
</div>
<% end -%>
应用程序/视图/插孔/ _form.html.erb:
<%= form_for [@jack.switch, @jack] do |f| %>
<% if @jack.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@jack.errors.count, "error") %> prohibited this jack from being saved:</h2>
<ul>
<% @jack.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :port %><br />
<%= f.number_field :port %>
</div>
<div class="field">
<%= f.label :jack_number %><br />
<%= f.text_field :jack_number %>
</div>
<div class="field">
<%= f.label :room_number %><br />
<%= f.text_field :room_number %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我已经尝试从Stack Overflow上的几个类似问题中实现一些代码,但似乎没有任何效果。任何帮助将非常感激。此外,如果您想查看其他任何代码,请告诉我。
再次感谢!
答案 0 :(得分:1)
您是否尝试从父资源构建@jack对象?即。
def new
# find Jack's parent
parent = JacksParent.find(:parent_id)
@jacks = parent.jacks.build(:switch_id => params[:switch_id])
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @jack }
end
end