簡體   English   中英

如何在Rails ActiveRecord中創建,關聯和取消關聯相關記錄與accepts_nested_attributes_for

[英]How can I create, associate, and de-associate related records in Rails ActiveRecord with accepts_nested_attributes_for

我在兩個模型之間有一個典型的has_many關系(比如文章has_many作者。)

我的文章表單讓用戶:

  1. 創建新作者並將其與文章相關聯,
  2. 選擇要與文章關聯的現有作者,
  3. 刪除與作者的關聯(不刪除作者記錄。)

我正在使用accepts_nested_attributes_for,這完全處理#1。 但是,我仍然在使用accepts_nested_attributes_for時找到實現#2和#3的最佳方法。

我實際上已經使用Rails 3.0.0。 ActiveRecord會在給定之前未曾見過的作者ID時自動創建新關聯。 但事實證明我無意中利用了隨后在Rails 3.0.1中修復的安全漏洞。

我嘗試了很多不同的方法,但沒有任何方法可以完全運行,在這種情況下我找不到有關最佳實踐的更多信息。

任何建議都會很感激。

謝謝,

羅素。

假設您可能需要使用連接表。 放手一搏:

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
      }
    ]
  }
}

為了完整性,我現在這樣做的方式是:

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

我還沒有找到一種方法來驗證相關模型(作者)的驗證。

看看這個: http//ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

它的rails 2.3,但大多數語法與rails3相同...它提到了你尋找的所有東西..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM