【发布时间】:2013-11-24 00:01:37
【问题描述】:
我正在尝试制作一个可以编辑然后保存的嵌套表单。每当我去保存表单时都会收到错误消息:
无法为 ID=11 的 Collection 找到 ID=11 的 ClassInstance
11 是表单中第一个 ClassInstance 的 ClassInstance id,看起来 Collection id 被设置为 NULL。
我尝试在控制器 form_for 中手动设置隐藏 ID,并在 _class_instance_fields.html.erb 中为 :collection_id 设置隐藏字段。
ActiveRecord 试图做什么,为什么会感到困惑?我是否在使用嵌套表单做一些你不应该做的事情?
我已经包含了我的一些代码,去掉了绒毛,这样就不用看太多了。
collections_controller.rb
def update
@collection = Collection.new(params[:collection])
if @collection.save
flash[:notice] = "IT WORKED"
else
flash[:notice] = "No Cigar...."
end
redirect_to collection_path
end
def read
@collection = Collection.find_by_user_id(current_user.id)
@classes = Classification.all
end
read.html.erb
<%= form_for @collection, url: {:action => "update", collection_id: @collection.id} do |f| %>
<%= f.hidden_field :id #I had hoped this would fix it%>
<table class="instance_table">
<%= f.fields_for :class_instances do |builder| %>
<%= render 'shared/class_instance_fields', :f => builder, :status => '0' %>
<% end %>
<tr><td>
<%= link_to_add_fields "Add an Instance", f, :class_instances %>
</td></tr>
</table>
<%= f.submit "Save"%>
<% end %>
_class_instance_fields.html.erb
<tr class="record_row">
<td>
<%= f.label( :name) %></p>
</td>
<%= f.hidden_field :status, :value => status %>
<%= f.hidden_field :collection_id %>
<td>
<% if status == '1' %>
<%= f.text_field :name %>
<% else %>
<%= link_to f.object.name, instance_edit_path(f.object.id) %>
<% end %>
</td>
<td>
<% if status == '1' %>
<%= f.select :classification, options_for_select(@classes.collect{|c| [c.name, c.id]},selected: f.object.class_id)%>
<% else %>
<%= f.label :classification, displayClassInstanceName(@classes.select{|a| a[:id] == f.object.class_id }[0]) %>
<% end %>
</td>
<td>
<% user = nil%>
<% id = nil %>
<% if status == '1' %>
<%collection = current_user.id %>
<% else %>
<%collection = f.object.collection_id %>
<% end %>
<%= f.label :username, displayUserName( user ) %>
</td>
<td>
<%= removeRecordLink(f) %>
</td>
</tr>
附加信息
在保存参数之前,我一直在使用Rails.logger.debug 检查参数。使用 `update
Rails.logger.debug "TG: " << params.to_yaml
我得到以下输出
TG: --- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
utf8: ✓
_method: put
authenticity_token: efvqGsLKJfdCsadfjsad9fsD97dfgYaOUjsg+uvAQi2+k4=
collection: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
name: mikee's Collection
class_instances_attributes: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
'0': !ruby/hash:ActiveSupport::HashWithIndifferentAccess
status: '0'
collection_id: '8'
_destroy: '0'
instance_attributes_attributes: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
'0': !ruby/hash:ActiveSupport::HashWithIndifferentAccess
id: '1'
_destroy: '0'
id: '11'
commit: Save
controller: collections
action: update
id: '8'
也许这可以帮助理解事情,因为我对参数没有太多经验,而且我不确定我应该在嵌套表单中看到什么。
【问题讨论】:
标签: ruby-on-rails forms activerecord nested-forms