Ruby on Rails 在锁定活动记录时是否自动锁定活动记录关联?
非常基本的问题:
我有一个模型 x,它有很多 y,模型 y 属于 x。
如果我锁定 ID 为 x_id 的模型 x 的实例,它是否还会锁定模型 y 表中关联列(在连接列下具有值 x_id)?
或者 ror 锁定只是锁定活动记录而不关心其关联?
谢谢!
Pretty basic question:
I have a model x that has_many y, and model y belong_to x.
If I lock an instance of model x with id x_id, does it also lock the associated rows in the table for model y which has has value x_id under the join column?
Or does ror locking just lock the active record and does not care about its associations?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,它不会锁定任何关联。它只是锁定行,而不关心模型关联。
From what i know, it would not lock any associations. It just locks rows, without caring for model associations.
好像rails中有两种锁定策略,乐观(它实际上并不锁定行,但 ActiveRecord 会针对同一行的多次更新引发 ActiveRecord::StaleObjectError [除了第一次更新,它将成功]),以及悲观(附加
FOR UPDATE
到 select 语句并实际锁定行(假设您的数据库不支持锁定)。 Locking.html" rel="nofollow">我读过的 ActiveRecord 锁定文档 暗示存在任何导致/允许锁定关联记录的魔法。由于您可以传递自己的锁定子句,因此我建议阅读您的特定数据库如何处理 Rails 用于悲观锁定的子句(
select ... for update
)以及您可以传递的其他子句(使用 ActiveRecord#lock!)。It seems as if there are two locking strategies in rails, optimistic (which doesn't actually lock rows but ActiveRecord raises ActiveRecord::StaleObjectError for multiple updates to the same row [except the first update, which will succeed]), and pessimistic (which appends
FOR UPDATE
to the select statement and actually locks the rows (assuming your database supports locking). None of the ActiveRecord Locking documentation I read through implies that there is any magic that causes/allows associative records to be locked.Since you can pass your own locking clause, I would suggest on reading up on how your specific database handles the clause rails uses for pessimistic locking (
select ... for update
) and other clauses that you can pass (Using ActiveRecord#lock!).