gpt4 book ai didi

ruby-on-rails - 更新 HABTM 模型关联只会删除关联

转载 作者:行者123 更新时间:2023-12-02 09:37:19 25 4
gpt4 key购买 nike

创建新的 HABTM 关联对我来说效果很好,但每次我尝试更新它们时,所有关联都会被删除。

这就是我的更新操作的样子。

def update
params[:dish][:cuisine_ids] ||= []
params[:dish][:diet_ids] ||= []

@user = current_user
@dish = @user.dishes_selling.find_by(:id => params[:id])

@dish.cuisines = Cuisine.where(:id => params[:dish][:cuisine_ids]) ### (1) ###
@dish.diets = Diet.where(:id => params[:dish][:diet_ids]) ### (1) ###

if @dish
respond_to do |format|
if @dish.update(dish_params) ### (2) ###
format.html { redirect_to dish_path(@dish), notice: 'Dish was edited.' }
else
format.html { render action: 'edit' }
end
end
else
flash[:error] = "You can only edit your dish!"
render :index
end
end

我的菜参数看起来像这样

    def dish_params
params.require(:dish).permit(:title, :desc, cuisine_ids: [:id], diet_ids: [:id])
end

如果在编辑时我单击两个美食复选框,则步骤 (2) 中的日志会显示此内容(仅注意 Delete 并且没有更新或插入 cuisine_dishes 表)

(0.1ms)  begin transaction
SQL (0.4ms) DELETE FROM "cuisines_dishes" WHERE "cuisines_dishes"."dish_id" = ? AND "cuisines_dishes"."cuisine_id" IN (7, 9) [["dish_id", 61]]
SQL (0.2ms) UPDATE "dishes" SET "desc" = ?, "updated_at" = ? WHERE "dishes"."id" = 61 [["desc", "yema1245"], ["updated_at", "2014-06-12 06:57:36.622811"]]
(5.5ms) commit transaction
Redirected to http://localhost:3000/dishes/61
Completed 302 Found in 48ms (ActiveRecord: 13.7ms)

问题:为什么更新 HABTM 关联会尝试删除该关联,而不是尝试创建新的关联(如果以前不存在),并删除(如果以前存在但不再存在)。

最佳答案

您应该尝试使用 << 运算符而不是 = ;

@dish.cuisines << Cuisine.where(:id => params[:dish][:cuisine_ids]).last

这应该添加而不是替换两个表中所需的 ID。

关于ruby-on-rails - 更新 HABTM 模型关联只会删除关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24178619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com