【发布时间】:2022-01-01 12:09:07
【问题描述】:
我很好奇是否可以在 rails postgresql 数据库中创建一个 type = text 的列,但是当调用该列时,将其中存储的任何内容转换为各种其他类型的数据(例如日期、整数等.)
就上下文而言,我正在创建一个工具,它允许创建一组问题并且许多用户可以回答这些问题。这些问题可以期待paragraph、number 或date 的回复。响应将存储在question_responses 表中。与其为各种响应类型(paragraph、number 和 date)创建 3 列,我更愿意创建一个名为 response 的单个文本列。然后,将存储在response 中的任何内容转换为text、integer 或date(根据需要)。想法?
这是我的模型:
# app/models/survey.rb
class Survey
has_many :questions
end
# app/models/question.rb
class Questions
belongs_to :survey
has_many :responses
enum response_type: { 'Paragraph': 0, 'Number': 1, 'Date': 2 }
end
# app/models/question_response.rb
# has column in db named "response" with type: text
class QuestionResponse
belongs_to :user
belongs_to :question
def converted_response
case question.response_type
when 'Paragraph'
response
when 'Number'
response.to_i
when 'Date'
response.to_date
end
end
end
# app/models/user.rb
class User
has_many :responses
end
【问题讨论】:
-
当然你可以这样做——只需要小心地将数据保持在一个一致的问题中并优雅地处理失败的转换。 convert_response 中的 begin...rescue 块将是一个良好的开始,而测试覆盖率则是一个更好的结束。
-
你也可以使用 Rails 内置的 serialize 方法将类型存储为 YAML。
标签: ruby-on-rails postgresql types