如何使用续集递归保存模型?

时间:2012-02-16 17:26:47

标签: ruby sequel

我一直在玩Sequel和Sequel :: Model。

我创建了GroupItems(one_to_many)。

我能做到:

Group.new << Item.new

但不是:

Group.new.add_item(Item.new)

也不:

Item.new.group=Group.new. 

抱怨Group没有主键。

如果我保存group,则会保存,但不会保存这些项目。

如何对所有内容进行递归保存?

1 个答案:

答案 0 :(得分:5)

设计续集不保存整个对象图。它的关联修改方法设计得非常直接,并没有提供很多抽象。

您可能希望使用nested_attributes插件或instance_hooks插件(nested_attributes插件在内部使用)。

# nested attributes plugin
Group.new(:items_attributes=>[{}]).save

# instance_hooks plugin
Group.new.after_save_hook{add_item(Item.new)}.save
相关问题