require "csv" class Doctrine < ApplicationRecord has_many :doctrine_jurisprudences, dependent: :destroy has_many :jurisprudences, class_name: "Cdao::Jurisprudence", through: :doctrine_jurisprudences has_many :doctrine_subjects, dependent: :destroy has_many :subjects, through: :doctrine_subjects has_many :annotations, dependent: :destroy validates :content, presence: true validates :content_fingerprint, uniqueness: true before_validation do self.content_fingerprint = Digest::SHA256.hexdigest(content) end def doctrine_subjects DoctrineSubject.where(doctrine_id: self.id) end def subjects Cdao::Subject.where(id: doctrine_subjects.map(&:subject_id)) end def subject_ids subjects.map(&:id) end def subject_ids=(ids) ids = ids.map(&:to_i) ids.each do |subject_id| record = DoctrineSubject.find_or_initialize_by(doctrine_id: self.id, subject_id: subject_id) next if record.persisted? record.save end DoctrineSubject.where(doctrine_id: self.id).each do |record| record.destroy unless ids.member?(record.subject_id) end subject_ids end def plain_content Sanitize.clean(content).strip end def self.parse_csv_file(parent_id, path) ::CSV.foreach(path).each_with_index do |data, index| row_no = index + 1 subject_name = data[0].strip headnote = data[1].strip content = data[2].strip doc_url = data[6].strip next if [headnote, content, doc_url].any?(&:blank?) parent = Cdao::Subject.find(parent_id) subject = parent.descendants.find_or_initialize_by(name: subject_name) if subject.new_record? subject.save subject.library_ids = [27] end logger = Logger.new(Rails.root.join("log/import.doctrines.log")) if subject.blank? logger.info "[#{row_no}] - no subject found" next end subject_id = subject.id doc_id = doc_url.split("?").first.split("/").map(&:strip).last record = self.find_or_initialize_by(headnote: headnote, content: ["
", content, "
"].join) if record.save record.library_subjects.find_or_create_by(library_id: 27) record.doctrine_jurisprudences.find_or_create_by(jurisprudence_id: doc_id) else logger.info "[#{row_no}] - failed to save #{record.errors.inspect}" end end end searchable do text :content integer :id integer :subject_ids, multiple: true integer :user_ids, multiple: true do paper_trail.originator.to_i end join(:phil_rep, :target => Annotation, :type => :string, :join => { :from => :annotation_doctrine_id, :to => :id }) date :created_at end end