3

私はこの2つのクラスを持っています、

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 の他のメソッドは、コレクションのメモリ内コピーに対してのみ機能します。オブジェクトを永続化するまで、実際には何も変更しません。

また、コレクションに対して実行されるすべての CRUD アクションは、主にターゲットに影響します。create() や destroy() などのいくつかは、多対多のコレクションで中間リソースを追加/削除しますが、これはターゲットの作成または削除の副作用にすぎません。

あなたの場合、最初の投稿だけを削除したい場合は、次のようにすることができます:

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

パーツは、最初のUser.first.posts.first(1)投稿のみを対象とするコレクションを返します。コレクションで destroy を呼び出すと、コレクション内のすべて (最初のレコードのみ) が削除され、仲介者が含まれます。

于 2009-11-30T07:05:17.463 に答える
0

I managed to do it by doing:

#to add
user_posts = User.first.posts
user_posts << Bolt.first
user_posts.save 

#to remove
user_posts.delete(Bolt.first)
user_posts.save

I think the only way to do it is by working with the instance actions, do your changes on that instance and after you finished, just save it.

It's kind of different from AR, but it should be fine though.

于 2014-08-11T13:12:19.083 に答える