📜 ⬆️ ⬇️

Datamapper many_to_many relationship update

Once when using Datamapper, I ran into the task of updating the many_to_many relationship collection, I rummaged through many sources, but I could not find an explanatory explanation. I want to present my decision.


So, we have 2 objects - Article (Article) and Category (Category). One Article may belong to different Categories and one Category may contain several Articles. Immediately create multiple categories.
class Article include DataMapper::Resource property :id, Serial property :name, String has n, :categories, :through => Resource end class Category include DataMapper::Resource property :id, Serial property :name, String has n, :articles, :through => Resource end category_d = Category.new category_d.name = " " category_d.save category_f = Category.new category_f.name = "" category_f.save category_v = Category.new category_v.name = "" category_v.save category_r = Category.new category_r.name = "" category_r.save 


We decided to create an article "Gerard Depardieu" and decided that it could be in several Categories - "Acting Actors", "French"
')
 article = Article.new article.name = " " article.save category_d = Category.first(:name => " ") category_f = Category.first(:name => "") article.categories << category_d article.categories << category_f article.save 


After some time we decided to make changes - remove the Article from the “Acting Actors” Category, add it to the “Winemakers” Category, and add to the “Russians” Category.
And here the most interesting thing happens because you can do it as described in the documentation — manually delete unwanted links and add new ones, and you can make it much easier - just assign an array of necessary links.
 article = Article.first(:name => " ") category_v = Category.first(:name => "") category_r = Category.first(:name => "") category_f = Category.first(:name => "") article.categories = [category_v, category_r, category_f] article.save 


I hope that my explanation will be useful, and if anyone knows the option easier - please tell in the comments.

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


All Articles