[英]Rails accepts_nested_attributes for: eliminating duplicates
假設我們有以下模型:
class User < ActiveRecord::Base
has_many :widgets
accepts_nested_attributes_for :widgets, allow_destroy: true
end
class Widget < ActiveRecord::Base
belongs_to :user
validates :title, presence: true, uniqueness: { scope: [:user_id] }
end
當我使用嵌套的窗口小部件屬性(包含重復的標題)保存用戶時,出現預期的驗證錯誤。 什么是避免驗證錯誤並在保存之前靜默消除重復條目的好方法?
謝謝。
如果嵌套屬性不符合某些條件,則可以拒絕它們:
accepts_nested_attributes_for :widgets,
allow_destroy: true,
reject_if: lambda { |w| Widget.pluck(:title).include?(w.title) && Widget.pluck(:user_id).include?(w.user_id) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.