Ruby on Rails:在单个数据库单元中保存多个值 [英] Ruby on Rails: Saving multiple values in a single database cell

查看:215
本文介绍了Ruby on Rails:在单个数据库单元中保存多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Ruby on Rails应用程序的单个单元记录中保存多个值?

How do I save multiple values in a single cell record in Ruby on Rails applications?

如果我有一个名为 Exp 教育经验技能,如果我想让用户在单行中存储多个值,如:教育机构或技能,最好的做法是什么?

If I have a table named Exp with columns named: Education, Experience, and Skill, what is the best practice if I want users to store multiple values such as: education institutions or skills in a single row?

例如,如果用户有多个技能,这些技能应该在一个单元格中?

For instance if user has multiple skills, those skills should be in one cell? Would this be best or would it be better if I created a new table for just skills?

请指教,

谢谢

推荐答案

我不建议在同一个数据库列中存储多个值。这将使查询非常困难。例如,如果您想查找具有特定技能集的所有用户,则查询将在可读性和性能方面笨拙。

I would not recommend storing multiple values in the same database column. It would make querying very difficult. For example, if you wanted to look for all the users with a particular skill set, the query would clumsy both on readability and performance.

但是,仍然存在某些情况

However, there are still certain cases where it makes sense.


  • 当您要允许数据点的变量列表时

  • 不会基于列表中的值之一查询数据

ActiveRecord内置了对此的支持。您可以在数据库列中存储 Hash Array

ActiveRecord has built-in support for this. You can store Hash or Array in a database column.


  1. 只需将列标记为文本

rails g model Exp experience:text education:text skill:text


  • 接下来,序列化模型代码中的列

    class Exp < ActiveRecord::Base
      serialize :experience, :education, :skill
      # other model code
    end
    

    li>

  • 现在,您只需将 Hash Array 数据库字段!

  • Now, you can just save the Hash or Array in the database field!

    Exp.new(:skill => ['Cooking', 'Singing', 'Dancing'])
    


  • 这篇关于Ruby on Rails:在单个数据库单元中保存多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆