我有这样两个类,DataMapper的有n个通过删除资源(从关联中删除)不工作
class User
include DataMapper::Resource
property :id, Serial
property :name, String
has n :posts, :through => Resource
end
class Post
include DataMapper::Resource
property :id, Serial
property :title, String
property :body, Text
has n :users, :through => Resource
end
所以一旦我有一个新的职位,如:
Post.new(:title => "Hello World", :body = "Hi there").save
我有严重的问题添加和从协会中删除,如:
User.first.posts << Post.first #why do I have to save this as oppose from AR?
(User.first.posts << Post.first).save #this just works if saving the insertion later
如何从该关联中删除帖子? 我使用以下,但肯定它不工作:
User.first.posts.delete(Post.first) #returns the Post.first, but nothing happens
User.first.posts.delete(Post.first).save #returns true, but nothing happens
User.first.posts.delete(Post.first).destroy #destroy the Post.first, not the association
所以,我真的不知道如何从BoltUser阵列删除。
感谢您的解释丹,你提到的这种方法也可以工作!欢呼 – zanona 2009-11-30 13:07:27
是不是create()已弃用?但我明白new()现在对集合的功能相同,所以User.first.posts.new()将创建并保留一条记录? – arbales 2009-12-19 06:25:45
不,不建议使用create()。 new()只是初始化内存中的资源。但它会将其链接到父对象,因此保存父对象也会导致孩子被保存。 – dkubb 2010-01-04 07:33:27