ruby-on-rails – 如何在Rails ActiveRecord中创建,关联和解除关
发布时间:2020-12-17 02:28:12 所属栏目:百科 来源:网络整理
导读:我在两个模型之间有一个典型的has_many关系(比如文章has_many作者.) 我的文章表单让用户: 创建新作者并将其与文章相关联, 选择要与文章关联的现有作者, 删除与作者的关联(不删除作者记录.) 我正在使用accepts_nested_attributes_for,这完全处理#1.但是,我仍
我在两个模型之间有一个典型的has_many关系(比如文章has_many作者.)
我的文章表单让用户: >创建新作者并将其与文章相关联, 我正在使用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 } ] } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |