DataMapper有n通过资源DELETE(从关联中删除)不起作用
我有这两节课,
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,如:
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
我该如何从该关联中删除post? 我正在使用以下但是它肯定不起作用:
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数组中删除它。
delete()方法和Array中的其他方法仅适用于集合的内存中副本。 在您持久保存对象之前,它们实际上不会修改任何内容。
此外,对集合执行的所有CRUD操作主要影响目标。 一些(如create()或destroy())将在多个集合中添加/删除中间资源,但这只是创建或删除目标的副作用。
在您的情况下,如果您只想删除第一个post,您可以这样做:
User.first.posts.first(1).destroy
User.first.posts.first(1)
部分返回一个仅限于第一个post的集合。 在集合上调用destroy会删除集合中的所有内容(这只是第一条记录)并包含中介。
我设法通过这样做:
#to add user_posts = User.first.posts user_posts << Bolt.first user_posts.save #to remove user_posts.delete(Bolt.first) user_posts.save
我认为唯一的方法是使用实例操作,在该实例上进行更改,完成后,只需保存即可。
它与AR有点不同,但它应该没问题。