我是否正確地說 Rails 將處理將關聯的 has_many 項添加到物件,如果您將引數與 tag_ids 之類的定義作為 ids 陣列一起傳遞?
如果是這樣,我將以下內容發布到我的專案控制器:-
{
"title": "Bottle",
"tag_ids": [25, 26]
}
發生的事情是 tag_ids 被忽略了。我已經添加了 id 為 25 的標簽,但沒有包含 26。
我的控制器:-
# PATCH/PUT /api/items/1
def update
if @item.update(item_params)
render json: @item, include: ['tags']
else
render json: @item.errors
end
end
def item_params
params.require(:item).permit(:name, :tag_ids)
end
專案has_and_belongs_to_many標簽,它們有一個連接表jobs_tags。該關聯有效,因為我在上面的回復中回傳了標簽。但是,我似乎無法添加它們。知道我哪里可能出錯了嗎?
我需要顯式地tag_ids向 Item 模型添加一個欄位嗎?
uj5u.com熱心網友回復:
tag_ids引數是一個陣列。但permit(:name, :tag_ids)只允許一個tag_ids屬性。
將權限更改為:
def item_params params.require(:item).permit(:name, tag_ids: []) end
有關更多詳細資訊,請參閱如何允許具有強引數的陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416222.html
標籤:
上一篇:在Windows10上運行geminstallmysql2時出現以下錯誤
下一篇:紅寶石|如何轉換郵件之類的數字?
