How to create this 'for each loop' in Ruby? -
given:
class author < activerecord::base has_many :articles end upon receipt of json file includes author's articles, i'd destroy articles in database author, not included in json file. how can create 'for each loop'?
article_collection = @author.articles.all unless article_collection.blank? article_collection.each |article_from_collection| # how can check on next line if it's id included in params? if article_from_collection.arti_id "is not part of" params[:author][:articles_attributes] article_from_collection.destroy end end end how can check on 5th line, on basis of arti_id included in params, whether article arti_id exists in json input?
should perhaps build collection of arti_ids in parameters , use .include? see each article in db, if in collection?
i tried 2 lines below. first returns false irrespective whether article included in json or not. second line returns error typeerror exception: no implicit conversion of symbol 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] returns like:
{ "some_other_attributes"=>[ {"key"=>"value", ...}, {...} ], "articles_attributes"=> [ {"arti_id"=>"string-id", "other_attributes"=>"value", ...}, {"arti_id"=>"string-id", "other_attributes"=>"value", ...} ] }
you activerecord query
article_ids = params[:author][:article_attributes].map |attrs| attrs[:arti_id] end @author.articles.where.not(id: article_ids).destroy_all this destroy articles author ids not in article attributes you've been given.
if you're confused query, creates not in query filters out articles passed in , destroys ones left over.
Comments
Post a Comment