【发布时间】:2018-09-21 14:46:16
【问题描述】:
我有一条 Customer 记录,与 Location 有多对多关联。
我目前在编辑客户页面上选中/取消选中我想要的特定客户的位置。当我取消选中所有位置并点击提交时,这些位置将从我的模型中删除,并且我的验证会引发错误。我本来希望这些位置不会被删除,因为我有需要它们存在的验证,这是我需要的。
我在Customer 模型中的验证。
validates :locations, presence: true
我的看法:
<% @locations.each do |i| %>
<li class="list-group-item">
<%= hidden_field_tag "customer[location_ids][]", '' %>
<%= check_box_tag "customer[location_ids][]", i.id, @customer.location_ids.include?(i.id) %>
<%= i.name %>
</li>
<% end %>
我的控制器:
@customer = Customer.find(params[:id])
@customer.assign_attributes(params.require(:customer).permit(:first_name, :middle_initial, :last_name, :location_ids => []))
@customer.save!
.save! 导致以下错误:
error Locations can't be blank
但是,当您刷新页面或查看数据库记录时,位置引用被破坏了,我还看到它们被 CLI 破坏了。我不明白为什么验证不能阻止位置引用被破坏。提前致谢。
【问题讨论】:
-
它们都被摧毁了,还是只有一个?您不必验证它们都必须在那里,只是至少必须有一个。
-
@EmilKampp 他们都被删除了。
-
您是否查看过通过
assign_attributes批量分配嵌套属性的文档?似乎在没有验证的情况下删除记录可能会有一个怪癖,并且只有在您调用save!时才会调用您的验证。 -
您可以在您的
Location模型中使用validates_associated :customer。此方法对关联运行验证。不过,我不确定这是否会在删除时发生。
标签: ruby-on-rails ruby ruby-on-rails-5