0

我有两个模型BoardCategory(使用祖先 gem 的树结构)与 has_many/belongs_to 关系。

当我创建新的 Board 实例时,我会自动为其创建根类别。我用 Board after_save 回调来做到这一点。

after_create do 
  categories.create(name: "Main Category", description: nil)
end

在我的另一个问题中,我得到了建议:

在外部模型/类上使用回调不是一个好习惯。Category 在 Board 之外,因此 Board 不应在它的回调中调用 Category,这应该是一个私人空间。相反,更好的方法是在 BoardsController 的 #create 中将根类别添加到板中

但另一方面,我听说过胖模型/皮肤控制器原理。那么在这种情况下,逻辑的良好做法是什么?

4

1 回答 1

0

你可以使用观察者

Observer classes respond to life cycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn't pertain to the core responsibility of the class

于 2013-07-12T19:17:41.370 回答