![](/img/trans.png)
[英]Rails how to reject_if when accepts_nested_attributes_for
[英]How to delete child during update with reject_if option for accepts_nested_attributes_for
我在Rails 5.0上。 我不太確定這是否可行,或者是否需要采用其他方法。 我有用於過程和復雜性的模型,其中過程has_many定義的復雜性如下:
class Procedure < ActiveRecord::Base
has_many :complications, dependent: :destroy
accepts_nested_attributes_for :complications, allow_destroy: true, reject_if: proc{|attr| attr[:name] == 'None'}
end
class Complication < ActiveRecord::Base
belongs_to :procedure
validates :name, presence: true
end
呈現給用戶的是嵌套表格,其中包含多種並發症。 我使用了繭寶石來動態地做到這一點。 在新記錄上,將為用戶顯示一個空的並發症選擇框。 如果他們將其保留為空,則驗證失敗。 這是為了迫使他們選擇“無”,以防止他們跳過該字段。 如果他們確實選擇了“無”,那么由於reject_if
選項,不會增加任何復雜性。 所有這些工作完全符合預期。
如果選擇了復雜功能(例如“失敗”)並隨后編輯了過程記錄,就會出現我遇到的問題。 如果將並發症更改為“無”,然后更新記錄,則當我想要的行為被破壞時,並發症將保持不變(即仍為“失敗”)。
如果更新中的記錄已經存在,則reject_if選項可能無法刪除該記錄。 這個對嗎? 如果是這樣,處理我的案件的適當方法是什么?
TIA。
您想要的是超出了reject_if
選項的范圍。
如果名稱為“ None”(空白或無),則可以通過更改列入白名單的參數以添加_destroy = '1'
來獲得功能。
class ProceeduresController
# ...
def update
end
private
# ...
# Only allow a trusted parameter "white list" through.
def proceedure_params
params.require(:proceedure)
.permit(:name,complications_attributes: [:id, :name, :_destroy])
end
def update_params
proceedure_params.tap do |p|
p["complications_attributes"].each do |a|
if a[:id].present? && ["None", nil, ""].includes?(a[:name])
a[:_destroy] = '1'
end
end
end
end
end
class Procedure < ActiveRecord::Base
has_many :complications, dependent: :destroy
accepts_nested_attributes_for :complications,
allow_destroy: true,
reject_if: :reject_attributes_for_complication?
def self.reject_attributes_for_complication?
return false if attr[:_destroy]
attr[:name] == 'None'
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.