HABTM 删除/推送,不带对象,仅 id

发布于 2024-11-08 10:51:41 字数 585 浏览 6 评论 0原文

我有一系列带有类别值的复选框,一个经典的 Items ><类别场景,与 has_and_belongs_to_many 关联。

问题是我不想找到对象来追加或删除关联,我只想使用 ID,即整数。

我真的很关心我的数据库,我不想做不必要的查询。我知道 ID 存在,并且 Item 存在,如果不存在,我也不在乎。我只想以干净的方式执行删除。

不!

@item.categories << @category
@item.categories.delete @category

是的!

@item.categories << id
@item.categories.delete id

或者,但是太脏了,

@category = Category.new
@category.id = id
@item.categories << @category
@item.categories.delete @category

大家有什么想法吗?

I have a series of check boxes with category values, a classical Items >< Categories scenario, associated with has_and_belongs_to_many.

The thing is I DON'T want to find the object to append or delete an association, I want to use only the ID, the integer.

I really take care of my database and I don't want to do unnecessary queries. I know that ID exists, and the Item exists, and if doesn't exist, I don't care. I just want to execute the delete in a clean way.

NO!

@item.categories << @category
@item.categories.delete @category

YES!

@item.categories << id
@item.categories.delete id

or, but so dirty

@category = Category.new
@category.id = id
@item.categories << @category
@item.categories.delete @category

Any thoughts guys?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

み青杉依旧 2024-11-15 10:51:41

您是否尝试过通过

@item.category_ids << id
@item.category_ids.delete id

这种方式获得一个整数数组(id),而不是一个包含对象的数组。

Have you tried

@item.category_ids << id
@item.category_ids.delete id

This way you get an array of integers (the ids), and not an array with the objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文