0
我一直在使用两种模式,并在嵌套属性上使用唯一性形成验证。dependent::destroy不能与validates_associated配合使用
保存表单时,唯一性验证的范围是列表用户的电子邮件地址。我遇到了一个错误,如果用户试图在一个事务中保存两封电子邮件,验证不会被触发,因为它会检查数据库中的现有记录,而不是将要保存的内存中的对象。
我的型号如下:
class List < ActiveRecord::Base
has_many :competitors, dependent: :destroy, inverse_of: :list
accepts_nested_attributes_for :competitors, reject_if: :all_blank, allow_destroy: true
end
class Competitor < ActiveRecord::Base
belongs_to :list, inverse_of: :competitors
validates :list, presence: true
validates :name, presence: true, length: { minimum: 2, maximum: 20 }
validates :email, presence: true, format: { with: User::EMAIL_REGEX }
validates :email, uniqueness: { scope: :list_id }
end
为了解决这个问题,我补充说:
validates_associated :competitors
进入我的列表模型,现在造成的形式表现为与审定发射了当预期用户试图为竞争对手保存两个相同的电子邮件地址。
但是,运行我的测试,我发现此块中的示例现在导致失败。
describe "@competitors" do
let!(:list) { FactoryGirl.create(:list) }
let!(:competitor) { FactoryGirl.create(:competitor, list_id: list.id) }
it "deletes associated competitors if the list is deleted" do
expect { list.destroy }.to change { Competitor.count }.by(-1)
end
end
我的研究,到目前为止告诉我,这是不是一个普遍的问题,所以我觉得我做错了什么,但我不能完全告诉那是什么。
我使用的是ruby 2.3.0和rails 4.2.7.1