Allow different types of data in the same field - Ruby On Rails

1

I have a logic query that I'm not sure how to solve, I'm doing a kind of survey, in which, when creating the questions, I need to specify the type of response it will receive, be it a text string, a Boolean data, a numeric data, etc. However, the field of the database is saved by default as "string", within the "Answer" table, in which way any type of data could be allowed, specifically in the field called "response" and that at the time to call it in sight return as such? I appreciate your suggestions

question.rb

class CreateQuestions < ActiveRecord::Migration[5.2]
  def change
    create_table :questions do |t|
      t.string :title
      t.references :survey, foreign_key: true

      t.timestamps
    end
  end
end

answer.rb

class CreateAnswers < ActiveRecord::Migration[5.2]
  def change
    create_table :answers do |t|
      t.string :response
      t.references :question, foreign_key: true

      t.timestamps
    end
  end
end
    
asked by Hector Hernandez 16.12.2018 в 19:50
source

1 answer

0

What I would do would be serialize the field.

class Answer < ActiveRecord::Base
  serialize :response
end

And in the bd leave the field as t.text :response instead of string , this way you would keep any type of data in the same field, including hashes or objects, and then you would recover it as is when you consult them.

    
answered by 16.12.2018 / 21:21
source