作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
"value", ...}, {...} ], "articles_attribut-6ren">
给定:
class Author < ActiveRecord::Base
has_many :articles
end
收到包含作者文章的 JSON 文件后,我想销毁数据库中作者的文章,但不包含在 JSON 文件中。我怎样才能为每个循环创建这个?
article_collection = @author.articles.all
unless article_collection.blank?
article_collection.each do |article_from_collection|
# How can I check on the next line if it's id is included in the params?
if article_from_collection.arti_id "is not part of" params[:author][:articles_attributes]
article_from_collection.destroy
end
end
end
我如何在第 5 行根据参数中也包含的 arti_id
检查 JSON 输入中是否存在具有该 arti_id
的文章?
我是否应该在参数中构建一个 arti_id
集合,然后使用 .include?
查看数据库中的每篇文章,如果它在这个集合中?
我尝试了下面的两行。第一个返回 false
无论文章是否包含在 json 中。第二行返回错误 TypeError Exception: no implicit conversion of Symbol into Integer
。
if params[:author][:articles_attributes].include? article_from_collection.arti_id
if params[:author][:articles_attributes][:arti_id].include? article_from_collection.arti_id
params[:author]
返回如下内容:
{ "some_other_attributes"=>[ {"key"=>"value", ...},
{...} ],
"articles_attributes"=> [ {"arti_id"=>"string-id", "other_attributes"=>"value", ...},
{"arti_id"=>"string-id", "other_attributes"=>"value", ...} ]
}
最佳答案
您可以使用 ActiveRecord 查询来做到这一点
article_ids = params[:author][:article_attributes].map do |attrs|
attrs[:arti_id]
end
@author.articles.where.not(id: article_ids).destroy_all
这将销毁其 id 不在您提供的文章属性中的作者的所有文章。
如果您对查询感到困惑,它只是创建一个 NOT IN
查询,过滤掉传入的文章,然后销毁剩下的文章。
关于ruby - 如何在 Ruby 中创建这个 'for each loop'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35037646/
我是一名优秀的程序员,十分优秀!