How to create, associate and de-associate related records in Rails ActiveRecord with accepts_nested_attributes_for

I have a typical has_many relationship between two models (let's say has_many Authors. Article)

My article form allows the user to:

  • Create new authors and link them to an article,
  • Select existing authors to link to.
  • Remove association with the Author (without deleting the author’s entry.)

I am using accepts_nested_attributes_for, and this works fine with C # 1. However, I have not yet found a better way to implement # 2 and # 3, still using accepts_nested_attributes_for.

It actually worked for me with Rails 3.0.0. ActiveRecord will automatically create a new association if an identifier of an author that he had not previously seen is set. But it turned out that I accidentally used a security bug that was fixed in Rails 3.0.1.

I tried a bunch of different approaches, but nothing works completely, and I can not find much information about best practices in this case.

Any advice would be appreciated.

Thanks,

Russell.

+4
source share
3 answers

Assuming you probably need to use a join table. Give this:

class Article < ActiveRecord::Base has_many :article_authors accepts_nested_attributes_for :article_authors, allow_delete: true end class Author < ActiveRecord::Base has_many :article_authors end class ArticleAuthor < ActiveRecord::Base belongs_to :article belongs_to :author accepts.nested_attributes_for :author end # PUT /articles/:id params = { id: 10, article_authors_attributes: { [ # Case 1, create and associate new author, since no ID is provided { # A new ArticleAuthor row will be created since no ID is supplied author_attributes: { # A new Author will be created since no ID is supplied name: "New Author" } } ], [ # Case 2, associate Author#100 { # A new ArticleAuthor row will be created since no ID is supplied author_attributes: { # Referencing the existing Author#100 id: 100 } } ], [ # Case 3, delete ArticleAuthor#101 # Note that in this case you must provide the ID to the join table to delete { id: 1000, _destroy: 1 } ] } } 
+2
source

Take a look at this: http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

for rails 2.3, but most of the syntax is the same as rails3 ... It mentions everything you're looking for ..

+1
source

For completeness, as I do now, these are:

 class Article < ActiveRecord::Base belongs_to :author, validate: false accepts_nested_attributes_for :author # This is called automatically when we save the article def autosave_associated_records_for_author if author.try(:name) self.author = Author.find_or_create_by_name(author.name) else self.author = nil # Remove the association if we send an empty text field end end end class Author < ActiveRecord::Base has_many :articles end 

I have not found a way to test the associated model (Author) with its checks.

+1
source

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


All Articles