通过嵌套表单创建多个关联对象时,不应用唯一性验证

时间:2014-04-25 13:37:46

标签: ruby-on-rails-3 validation nested-forms

我有以下模型和观点。

我发现当我尝试使用相同的序列同时创建多个设备时,不会抛出任何错误并创建所有设备。如果我正在尝试创建一个具有现有序列的设备,那么我会得到正确的错误。

如何更改唯一性验证,以便我无法同时创建两个具有相同序列的设备?

模型/ service.rb

class Service < ActiveRecord::Base
  attr_accessible :device_attributes
  has_many :devices
  accepts_nested_attributes_for :devices
end

模型/ device.rb

class Device < ActiveRecord::Base
  attr_accessible :serial
  belongs_to :service
  validates :serial, uniqueness: true
end

视图/服务/ _service_form.html.erb

<%= simple_nested_form_for @service do |f| %>
  <%= f.simple_fields_for :devices do |d| %>
    <%= d.input :serial %>
    <%= d.link_to_remove "Remove Device" %>
  <% end %>
  <%= f.link_to_add "Add Device", :devices %>
  <%= f.submit %>
<% end %>

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情:Validate uniqueness of a child object in a nested form not working correctly

或者:http://www.freezzo.com/2012/06/14/validating-uniqueness-of-nested-model-on-create

或合并两个例子:

class Service < ActiveRecord::Base
   ...
   validate :uniqueness_of_devices

   private 
      def uniqueness_of_devices
        ids = self.devices.map {|d| d.id}
        if ids.detect{|i| ids.count(i) > 1 } == 1
           errors.add(:devices, "some message")
        end
       end
end