DataMapper has n through Resource DELETE (Remove from association), does not work

I have two classes,

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, as soon as I get a new message like:

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

I'm having serious problems adding and removing from the association, for example:

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 do I remove a message from this association? I am using the following, but definitely 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

So I really don't know how to remove this from the BoltUser array.

+3
source share
2 answers

The delete () method and other methods from the array work only in copies of collections in memory. In fact, they do not change anything until you save the objects.

, CRUD, , . , create() destroy(), / , .

, , :

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

User.first.posts.first(1) , . ( ) .

+4

:

#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, .

0

Source: https://habr.com/ru/post/1724220/


All Articles