Arb
Arb

Reputation: 77

Create data from another model

I have 2 models: translation_file and translation_group, I upload files in translation_file and the data from those files I want to stock them in translation_group, I'm trying to use the after_create.

in my models/translation_file.rb:

class TranslationFile < ApplicationRecord
  has_many_attached :yaml_files
  after_create :file_to_data

  def file_to_data
    hash = YAML.load_file()#our file here
    t = load_translation(hash)
    #hash to translation_group
  end
end

Does anyone knows a way to do it?

Upvotes: 1

Views: 70

Answers (2)

Arb
Arb

Reputation: 77

With the help of a friend, we created a new Class on /lib that we included in TranslationFile and since I was using Active Storage from Rails 5.2 we had play with the blob.

require 'translation_file_processor'

class TranslationFile < ApplicationRecord
  has_one_attached :file
  after_create :transform_to_translation_groups

  def transform_to_translation_groups
    p = TranslationFileProcessor.new file.blob
    p.process
    true
  end

end

in the lib/translation_file_processor.rb

class TranslationFileProcessor
   include ActiveStorage::Downloading
   attr_reader :blob
   attr_accessor :translations_hash

    def initialize(blob)
      @blob = blob
    end

    def process
      download_blob_to_tempfile do |file|
        ...
      end
      #hash to translation_group
      ...
      group = TranslationGroup.new
      ...
      group.save
    end
end

Upvotes: 1

Sovalina
Sovalina

Reputation: 5609

You can create/find any TransitionGroup you need inside the method:

def file_to_data
  hash = YAML.load_file()#our file here
  t = load_translation(hash)
  group = TransitionGroup.find_by( #any attribute you want)
  #or TransitionGroup.new

  group.attribute_for_storing_data = t
  group.save
end

Upvotes: 1

Related Questions