Rails 中批量删除 has_many 关联行
我有一个模型 Foo 和一个模型 Bar,两者都有 has_many :bar_foos (然后彼此都有 has_many :through => :bar_foos)。通过 BarsFoo 模型,Foo 和 Bar 之间存在简单的多:多关系。
我想删除 bar_foos 表中的几行。具体来说,我想删除与任何给定的 Foo 集和任何给定的 Bar 集相关的任何 bar_foo 记录。为了提高性能,我想发出一个数据库调用来执行此操作。
相应的 SQL 语句为:
DELETE FROM bar_foos WHERE bar_id IN ( ?, ?, ? ) AND foo_id in ( ?, ?, ? )
...同时用适当的 ID 替换 ?
。
如何使用 Rails 2.3.x 执行此操作?
理想情况下,我不会自己编写实际的 SQL,而是调用 ActiveRecord 方法。然而,我怀疑这种情况是否存在。
除此之外,我将自己编写 SQL 语句,但是:
- 我想避免对 SQL 字符串中的表/列名称进行硬编码
- 我想使用某种自动(即:可靠)方法来转义 SQL参数与仅连接字符串。
I have a model Foo and a model Bar, both of which has_many :bar_foos (and then has_many each other :through => :bar_foos). It's a simple many:many relationship between Foo and Bar, through a BarsFoo model.
I want to delete several rows in the bar_foos table. Specifically, I want to delete any bar_foo record that relates to any of a given set of Foos and any of a given set of Bars. For performance, I'd like to issue a single database call to do this.
The corresponding SQL statement would be:
DELETE FROM bar_foos WHERE bar_id IN ( ?, ?, ? ) AND foo_id in ( ?, ?, ? )
...while replacing the ?
s with the appropriate IDs.
How do I perform this using Rails 2.3.x?
Ideally, I'd to not write the actual SQL myself, but make ActiveRecord method calls instead. However, I doubt this exists.
Barring that, I'll craft the SQL statement myself, but:
- I'd like to avoid hardcoding the table/column names in the SQL string
- I'd like to use some sort of automatic (ie: reliable) method to escape the SQL parameters vs. just concatenating strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为使用关联是不可能的,你必须自己编写它(使用 destroy_all)
I think it's not possible using assosciation you have to write it your own (Use destroy_all)
你可以这样做...
这将销毁属于刚刚被销毁的对象的所有 bar_foos。
You can do this...
And that will destroy all the bar_foos that belong to the object that was just destroyed.