【问题标题】:DataMapper has n through Resource DELETE (Remove from association) not workingDataMapper 通过 Resource DELETE(从关联中删除)有 n 不起作用
【发布时间】:2010-12-21 09:40:06
【问题描述】:

我有这两个课,

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

【问题讨论】:

    标签: ruby-on-rails ruby datamapper has-and-belongs-to-many


    【解决方案1】:

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

    此外,对集合执行的所有 CRUD 操作主要影响目标。一些,如 create() 或 destroy(),会在多对多集合中添加/删除中间资源,但这只是创建或删除目标的副作用。

    在您的情况下,如果您只想删除第一个帖子,您可以这样做:

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

    User.first.posts.first(1) 部分返回一个仅适用于第一个帖子的集合。对集合调用 destroy 会删除集合中的所有内容(这只是第一条记录)并包括中介。

    【讨论】:

    • 感谢丹的解释,你提到的这种方法也很有效!干杯
    • 不推荐使用 create() 吗?但我知道 new() 现在对集合的功能相同,因此 User.first.posts.new() 将创建并保留记录?
    • 不,不推荐使用 create()。 new() 只是初始化内存中的资源。但是,它确实将其链接到父对象,因此保存父对象也会导致子对象也被保存。
    【解决方案2】:

    我设法做到了:

    #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 有点不同,但应该没问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2014-07-24
      • 1970-01-01
      • 2021-03-01
      相关资源
      最近更新 更多