2009-11-29 40 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,但它應該沒問題。