2009-11-29 56 views
3

我有这样两个类,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阵列删除。

回答

4

来自Array的delete()方法和其他方法仅适用于Collections的内存中副本。除非你坚持这些对象,否则它们实际上不会修改任何东西。

此外,集合上执行的所有CRUD操作主要影响目标。少数像create()或destroy()一样,会添加/删除多个到多个集合中的中间资源,但这只是创建或移除目标的副作用。

在你的情况,如果你想只删除后的第一次,你可以这样做:

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

User.first.posts.first(1)部分返回集合作用域只有第一篇文章。在集合上调用销毁会删除集合中的所有内容(这只是第一条记录),并包含中介。

+0

感谢您的解释丹,你提到的这种方法也可以工作!欢呼 – zanona 2009-11-30 13:07:27

+0

是不是create()已弃用?但我明白new()现在对集合的功能相同,所以User.first.posts.new()将创建并保留一条记录? – arbales 2009-12-19 06:25:45

+0

不,不建议使用create()。 new()只是初始化内存中的资源。但它会将其链接到父对象,因此保存父对象也会导致孩子被保存。 – dkubb 2010-01-04 07:33:27

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,但它应该没问题。