There are two tables - Rubric and Question . Connection many to many. The task is to upload data to the database via seeds.rb . Data is stored in xls. In principle, it is clear how to load the headings - we take all the data from the heading cells, split them by comma, combine and fill in the database. It is not clear how to bind Questions to these created headings. Or somehow make a request to the database? Tell me the correct option.

 | β„– вопроса | Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ | Вопрос | Π ΡƒΠ±Ρ€ΠΈΠΊΠ° | |:-----------|------------:|:------------:|:------------:| | 1 | Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ1 | Вопрос1 | Π½Π°ΡƒΠΊΠ°, ΠΏΠΎΠ»ΠΈΡ‚ΠΈΠΊΠ° | 2 | Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ2 | Вопрос2 | Турналистика | 3 | Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ3 | Вопрос3 | ΠΏΠΎΠ³ΠΎΠ΄Π° | 4 | Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ4 | Вопрос4 | Π½Π°ΡƒΠΊΠ° | 5 | Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ5 | Вопрос5 | Π·ΠΈΠΌΠ°, Π»Π΅Ρ‚ΠΎ, осСнь 

    1 answer 1

    In the table you have the names of headings separated by commas. An array of rubric titles for each question. In the Question model, you can declare a virtual attribute for these names (only a setter is needed). And in it by the accepted array - to associate the Question record with the Rubric records, finding or creating them by name.

    Here is an example of a setter in the Question model:

     class Question < ApplicationRecord has_many :rubrics, through: :rubrics_questions has_many :rubrics_questions def rubric_names=(value) return if value.blank? self.rubrics = value.split(', ').map { |name| Rubric.where(name: name).first_or_initialize } end end 

    And in seeds.rb questions are created like this:

     Question.where(id: id).first_or_create(title: title, text: text, rubric_names: rubric_names)