From c7468ae9c79a4e45e565476d3cfed0f9dd6f4d0f Mon Sep 17 00:00:00 2001 From: Giovanne Marcelo <gms15@inf.ufpr.br> Date: Wed, 24 Feb 2016 11:03:15 -0300 Subject: [PATCH] Fixing bug --- app/models/topic.rb | 4 +-- app/services/topics_importer.rb | 46 +++++++++++++++++++++++++-------- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/app/models/topic.rb b/app/models/topic.rb index 8ae4f4662..345683c37 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -1,8 +1,8 @@ class Topic < ActiveRecord::Base has_and_belongs_to_many :learning_objects - has_many :topic_relationships, foreign_key: "parent_id", dependent: :destroy, autosave: true - has_many :subtopics, through: :topic_relationships, source: :child, autosave: true + has_many :topic_relationships, foreign_key: "parent_id", dependent: :destroy + has_many :subtopics, through: :topic_relationships, source: :child has_many :topic_highlights, dependent: :destroy diff --git a/app/services/topics_importer.rb b/app/services/topics_importer.rb index ab589634e..1acf80432 100644 --- a/app/services/topics_importer.rb +++ b/app/services/topics_importer.rb @@ -4,38 +4,63 @@ class TopicsImporter def initialize items @items = items @@topics = {} + @@topics_relations = [] end def import - topics = [] + relations = [] @items.each do |learning_object| + lo_topics = parse_topics ( learning_object.get_metadata_values_of "dc.subject.category" ) + lo_topics.each_with_index do |topic_name, i| next if topic_exists? topic_name topic = Topic.where(name: topic_name).new - topic.learning_objects << learning_object - - create_relations(@@topics[lo_topics[i - 1]], topic) unless i == 0 - + create_relations(lo_topics[i - 1], topic_name) unless i == 0 @@topics[topic_name] = topic - end end + separate_relations() + end - Topic.import @@topics.values, recursive: true + Topic.import @@topics.values + import_topics_relations() end private - def create_relations parent_topic, topic - parent_topic.subtopics << topic + def create_relations parent_name, child_name + @@topics_relations.push(parent_name) + @@topics_relations.push(child_name) + end + + def separate_relations + @@topics_relations.push nil + end + + def import_topics_relations + + relations = [] + + @@topics_relations.each_with_index do |relation, i| + unless relation.nil? || @@topics_relations[i - 1].nil? + parent_id = Topic.find_by_name(@@topics_relations[i - 1]).id + child_id = Topic.find_by_name(relation).id + unless TopicRelationship.exists?(parent_id: parent_id, child_id: child_id) || i == 0 + relations.push TopicRelationship.where(parent_id: parent_id, child_id: child_id ).new + end + end + end + + TopicRelationship.import relations + end def parse_topics values @@ -44,12 +69,11 @@ class TopicsImporter values.each do |value| topics = value.split('::') end - topics + topics.map{|topic| topic.strip} end def topic_exists? (topic_name) Topic.exists? name: topic_name || !@@topics[topic_name].nil? end - end -- GitLab