如何锁定模型的关联集合?

时间:2011-01-25 07:54:19

标签: ruby-on-rails locking associations

我有

class Foo
  has_many :widgets
end

我想用锁定的选择拉出所有小部件。所以,我想做相同的事情:

@widgets_to_work_with = Widget.find_all_by_foo_id(@foo.id, :lock => true)

使用更好的代码,例如:

@widgets_to_work_with = @foo.widgets(:lock => true)

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

你可以在Foo ActiveRecord中重新定义方法小部件,或者更安全,添加另一种方法 a.e。

# in Foo.rb
#...
def self.locked_widgets
  Widget.find_all_by_foo_id(self.id, :lock => true)
end

希望可能有用