3

我有一個Rails 4.1應用程序正在使用一些值得注意的技術。accept_nested_attributes_for:allow_destroy,:_destroy不起作用

簡單的形式,繭

我具有嵌套屬性麻煩銷燬記錄。基於一些長期的研究,我相信我的代碼是正確的,但是我可能會錯過一些愚蠢的東西。

型號

has_many :staff_services_joins, :dependent => :destroy 
has_many :services, :through => :staff_services_joins 
accepts_nested_attributes_for :staff_services_joins, :allow_destroy => true 

這是一個有點非正統的,但我對加入模型中的兩個部件不屬於外鍵,需要進行設置。這就是爲什麼我接受連接模型而不是服務模型的嵌套屬性。

控制器方法

def update 
ap staff_params 
# if @staff_member.update_with_account staff_params, params[:password] 
if @staff_member.update_attributes staff_params 
    flash[:notice] = 'Successfully updated staff member! :)' 
    redirect_to vendor_store_staff_path current_store, @staff_member 
else 
    flash[:error] = 'Failed to update staff member :(' 
    render :edit 
end end 

斯特朗參數

params.require(:staff).permit(
    :user_id, 
    :store_id, 
    :avatar, 
    :remote_avatar_url, 
    :first_name, 
    :last_name, 
    :email, 
    :active, 
    :admin, 
    :staff_services_joins_attributes => [ 
     :staff_id, 
     :service_id, 
     :price, 
     :duration, 
     :_destroy 
    ] 
) 

實施例更新PARAMS散列

{ 
"store_id" => "2", 
"avatar" => "avatar.png", 
"remote_avatar_url" => "", 
"first_name" => "Joshua", 
"last_name" => "Tyree", 
"email" => "[email protected]", 
"active" => "0", 
"admin" => "1", 
"staff_services_joins_attributes" => { 
    "0" => { 
     "service_id" => "2", 
     "price" => "50.00", 
     "duration" => "30", 
     "_destroy" => "1" 
    } 
} 

}

基於該有,這個東西應該b摧毀該模型,但由於某種原因,它肯定不是。任何幫助是絕對讚賞。

+0

好吧,只需在'staff_services_joins_attributes:[..'中加入':id'並嘗試。 – 2015-04-06 13:06:40

+0

有趣的是,這確實解決了問題。只是讓我明白爲什麼,是否因爲ActiveRecord無法通過數組索引來辨別與數據庫中相關的記錄? – 2015-04-06 13:18:22

回答

6

爲了使用accepts_nested_attributes_for強參數,則需要指定嵌套的屬性應該是白名單。你做到了,但你錯過了添加:id這是需要執行刪除操作。 "_destroy"鍵標記刪除記錄,但要找到記錄並刪除內部,它需要在那裏有:id

你可以閱讀Removing Objects指南。