DataMapper 通过资源删除(从关联中删除)无法正常工作
-
07-07-2019 - |
题
我有这两节课
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 数组中删除它。
解决方案
delete()方法和Array中的其他方法仅适用于集合的内存中副本。在您持久保存对象之前,它们实际上不会修改任何内容。
此外,对集合执行的所有CRUD操作主要影响目标。一些(如create()或destroy())将在多个集合中添加/删除中间资源,但这只是创建或删除目标的副作用。
在您的情况下,如果您只想删除第一个帖子,则可以执行此操作:
User.first.posts.first(1).destroy
User.first.posts.first(1)
部分返回一个仅限于第一篇文章的集合。在集合上调用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 有点不同,但应该没问题。
不隶属于 StackOverflow