代码之家  ›  专栏  ›  技术社区  ›  zanona oldmanwiggins

DataMapper有n个通过资源删除(从关联中删除)不工作

  •  3
  • zanona oldmanwiggins  · 技术社区  · 16 年前

    我有这两个班,

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

    2 回复  |  直到 11 年前
        1
  •  4
  •   dkubb    16 年前

    delete()方法和数组中的其他方法只对集合的内存中副本有效。在持久化对象之前,它们实际上不会修改任何内容。

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

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

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

    这个 User.first.posts.first(1) 部分返回范围仅限于第一个日志的集合。对集合调用destroy将删除集合中的所有内容(这只是第一条记录),并包括中介。

        2
  •  0
  •   Sam    11 年前

    我设法做到了:

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

    推荐文章