[英]rails accepts_nested_attributes_for :reject_if not working
[英]accepts_nested_attributes_for, reject_if and has_one relationship not working together?
在我的模型中,我有
has_one :order, dependent: :destroy
accepts_nested_attributes_for :order, reject_if: lambda { |order| order[:description].blank? }, allow_destroy: true
出於某種原因,盡管reject_if已經過測試並且返回true(我使用調試器檢查過),但是嵌套順序不會被銷毀。
在互聯網上有很多關於這種現象的文章,但我找不到解決方案。
有人知道如何解決這個問題嗎?
我終於在這個特定場合創建了一個智能“reject_if”設置destroy標志,如Destroy on blank nested屬性所述 ,但是,對於我自己的規范,這不是很“紅寶石”,所以無法想象沒有更好的解...
accepts_nested_attributes_for :order, allow_destroy: true, reject_if: lambda { |attributes|
exists = attributes['id'].present?
empty = attributes[:description].blank?
attributes.merge!({_destroy: 1}) if exists and empty
return (!exists and empty)
}
來自nested_attributes API
您還可以設置:reject_if proc,如果它們未能通過您的條件,則會靜默忽略任何新的記錄哈希值。
params = { member: {
name: 'joe', order_attributes: [
{ description: 'Kari, the awesome Ruby documentation browser!' },
{ description: 'The egalitarian assumption of the modern citizen' },
{ description: '', _destroy: '1' } # this will be ignored
]
}}
任何具有空白description
哈希都將被完全忽略,即使它具有_destroy
標志。
如果你想刪除帶有空白描述的記錄,我可以想到兩個解決方案
選項1:在您的模型中使用回調刪除它們:
before_save :remove_orders_without_description
def remove_orders_without_description
orders.select{|o| o.description.blank?}.each(&:delete)
end
選項2:刪除模型定義中的reject_if
選項,並在視圖中使用JS來適當地設置_delete
屬性
嘗試這個
accepts_nested_attributes_for :order, reject_if: lambda { |order| order[:_destroy].blank? && order[:description].blank? }, allow_destroy: true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.