我使用Rails 5.1并且我在归档表单中有一个嵌套属性,它在选择字段中显示多个硬盘:
<%= form_with(model: archive, local: true, url: archive_path(@archive), method: :put) do |form| %>
<div class="field">
<%= form.label :shelfmark %><br />
<%= form.text_field :shelfmark %>
</div>
<div class="field">
<%= form.label "Harddisk" %><br />
<%= form.select :harddisk_id, Harddisk.order(bezeichnung: :asc).collect {|a| [ a.label, a.id ] } %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
在archives_controller中:
def archive_params
params.require(:archive)
.permit(:shelfmark, :harddisk_id, harddisk_attributes: [:id, :label])
end
当我选择ID为2的硬盘时,它不会更新存档表上的harddisk_id属性。它仍然使用harddisk_id:1(而不是2)。
rails服务器日志:
Started PATCH "/archives/5" for ::1 at 2018-02-09 13:52:10 +0100
Processing by ArchivesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"aas9eTl1Vb0JP+KHncyBKts7s1ZJD4l0jRz9wiNi3aiwwDYwkJbt9FXAy6T23sNYONJB1npoprvFtULReEKWIQ==",
"archive"=>{"shelfmark"=>"bar", "harddisk_attributes"=>
{"id"=>"1"}, "harddisk_id"=>"4"}, "commit"=>"Update Archive", "id"=>"2"}
Archive Load (0.4ms) SELECT `archive`.* FROM `archive` WHERE `archive`.`id` = 2 LIMIT 1
(0.3ms) BEGIN
Harddisk Load (0.5ms) SELECT `harddisks`.* FROM `harddisks` WHERE `harddisks`.`id` = 4 LIMIT 1
(0.2ms) ROLLBACK
现在它尝试更新harddisk_id记录,但抛出错误:
ActiveRecord :: RecordNotFound(无法找到ID为1的Harddisk for 存档ID = 2):
答案 0 :(得分:1)
如果您只想更新:
archive.harddisk_id
并且不更新任何关联的硬盘属性:
archive.attribute.capacity
archive.attribute.created_at
archive.attribute.updated_at
然后,您不需要nested_attributes
。所以:
替换所有
form.fields_for :harddisk do ... end
...与...
form.select :harddisk_id
此外,您现在可以安全地删除任何痕迹的nested_attributes,因为您不再需要它们了:
harddisk_attributes
archive_params
accepts_nested_attributes_for :harddisk
模型上的Archive
。