Ruby on rails 接受嵌套的属性并验证的唯一性
中心问题:在从嵌套表单进行批量分配期间,如何通过键合并属性集合 详细信息:我正在使用以下型号:Ruby on rails 接受嵌套的属性并验证的唯一性,ruby-on-rails,attributes,nested-forms,has-many,unique-constraint,Ruby On Rails,Attributes,Nested Forms,Has Many,Unique Constraint,中心问题:在从嵌套表单进行批量分配期间,如何通过键合并属性集合 详细信息:我正在使用以下型号: class Location < ActiveRecord::Base has_many :containers, :dependent => :destroy, :order => "container_type ASC" validates_associated :containers accepts_nested_attribut
class Location < ActiveRecord::Base
has_many :containers,
:dependent => :destroy,
:order => "container_type ASC"
validates_associated :containers
accepts_nested_attributes_for :containers,
:allow_destroy => true,
:reject_if => proc {|attributes| attributes["container_count"].blank? }
end
class Container < ActiveRecord::Base
belongs_to :location, :touch => true
validates_presence_of :container_type
validates_uniqueness_of :container_type, :scope => :location_id
validates_numericality_of :container_count,
:greater_than => 0,
:only_integer => true
end
从本质上说,助手向集合中添加了一个新容器,但所有类型都已关联或集合中已有一个新容器除外。此容器已预初始化为第一个尚未定义的容器类型。到目前为止,效果相当不错。添加容器是有效的。删除容器是有效的
问题是:我想实现选择和添加一个已经在集合中的容器类型应该合计它们的计数(相反,这将违反unique约束)。我不确定如果不为magic实现/重新设计完整的accepts\u nested\u attributes\u,最好的方法是什么-实际上我想通过使用它来减少-而不是增加-代码和复杂性
<% remote_form_for [:admin, setup_containers(@location)] do |f| -%>
<% f.fields_for :containers do |container_form| -%>
<%= render "admin/containers/form", :object => container_form %>
<% end -%>
<%= f.submit "Speichern" %>
<% end -%>
<% div_for form.object do -%>
<span class="label">
<%- if form.object.new_record? -%>
<%= form.select :container_type, { "Type1" => 1, "Type2" => 2, ... } %>
<%- else -%>
<%= form.label :container_count, "#{form.object.name}-Container" %>
<%= form.hidden_field :container_type %>
<%- end -%>
</span>
<span class="count"><%= form.text_field :container_count %></span>
<%- unless form.object.new_record? -%>
<span class="option"><%= form.check_box :_destroy %> Löschen?</span>
<%- end -%>
<% end -%>
def setup_containers(location)
return location if location.containers.any? {|l| l.new_record? }
returning location do |l|
all_container_types = [1, 2, ...]
used_container_types = l.containers.try(:collect, &:container_type) || []
next_container_type = (all_container_types - used_container_types).first
l.containers.build :container_type => next_container_type if next_container_type
end
end