我有這樣兩個類,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陣列刪除。
感謝您的解釋丹,你提到的這種方法也可以工作!歡呼 – zanona 2009-11-30 13:07:27
是不是create()已棄用?但我明白new()現在對集合的功能相同,所以User.first.posts.new()將創建並保留一條記錄? – arbales 2009-12-19 06:25:45
不,不建議使用create()。 new()只是初始化內存中的資源。但它會將其鏈接到父對象,因此保存父對象也會導致孩子被保存。 – dkubb 2010-01-04 07:33:27