DataMapper通过资源DELETE(从关联中删除)有n个不起作用 [英] DataMapper has n through Resource DELETE (Remove from association) not working

查看:61
本文介绍了DataMapper通过资源DELETE(从关联中删除)有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

所以一旦我有新帖子,例如:

So once I have a new post like:

Post.new(:title => "Hello World", :body = "Hi there").save

我在添加和删除关联时遇到严重问题,例如:

I'm having serious problems to add and remove from the association, like:

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

我应该如何从该关联中删除帖子?
我正在使用以下内容,但绝对不能使用:

And how should I remove a post from that association? I'm using the following but definitely its not working:

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

So I really don't know how to delete this from the BoltUser Array.

推荐答案

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

The delete() method, and other methods from Array only work on the in-memory copy of the Collections. They don't actually modify anything until you persist the objects.

此外,对集合执行的所有CRUD操作都会主要影响目标。诸如create()或destroy()之类的少数工具会在许多收藏集中添加/删除中间资源,但这只是创建或删除目标的副作用。

Also, all CRUD actions performed on a collection primarily affect the target. A few, like create() or destroy(), will add/remove the intermediary resources in many to many collections, but it's only a side effect of creating or removing the target.

在您的情况下,如果您只想删除第一个帖子,则可以执行以下操作:

In your case, if you wanted to remove just the first Post, you could do this:

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

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

The User.first.posts.first(1) part returns a collection scoped to only the first post. Calling destroy on the collection removes everything in the collection (which is just the first record) and includes the intermediaries.

这篇关于DataMapper通过资源DELETE(从关联中删除)有n个不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆