3

我有这两个课,

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 数组中删除它。

4

2 回答 2

4

delete() 方法和 Array 中的其他方法仅适用于 Collections 的内存副本。在您持久化对象之前,它们实际上不会修改任何内容。

此外,对集合执行的所有 CRUD 操作主要影响目标。一些,如 create() 或 destroy(),将添加/删除多对多集合中的中间资源,但这只是创建或删除目标的副作用。

在您的情况下,如果您只想删除第一个帖子,您可以这样做:

User.first.posts.first(1).destroy

User.first.posts.first(1)部分返回一个范围仅限于第一篇文章的集合。对集合调用 destroy 会删除集合中的所有内容(这只是第一条记录)并包括中介。

于 2009-11-30T07:05:17.463 回答
0

我设法做到了:

#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 有点不同,但应该没问题。

于 2014-08-11T13:12:19.083 回答