Создать данные из другой модели - PullRequest
0 голосов
/ 09 мая 2018

У меня есть 2 модели: translation_file и translation_group, я загружаю файлы в translation_file и данные из этих файлов, которые я хочу сохранить их в translation_group, я пытаюсь использовать after_create.

в моих моделях / 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

Кто-нибудь знает способ сделать это?

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

С помощью друга мы создали новый класс для / lib, который мы включили в TranslationFile, и, поскольку я использовал Active Storage из Rails 5.2, мы поиграли с 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

в 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
0 голосов
/ 09 мая 2018

Вы можете создать / найти любой TransitionGroup, который вам нужен внутри метода:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...