Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Saving multiple values in a single database cell

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

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?

I'd like to have users use multiple text fields, but should go into same cell record.

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?

Please advise,

Thanks

like image 954
hellomello Avatar asked Oct 13 '25 01:10

hellomello


2 Answers

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.

  • When you want to allow for variable list of data points
  • You are not going to query the data based on one of the values in the list

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

  1. Just mark the columns as Text

    rails g model Exp experience:text education:text skill:text
    
  2. Next, serialize the columns in your Model code

    class Exp < ActiveRecord::Base
      serialize :experience, :education, :skill
      # other model code
    end
    
  3. Now, you can just save the Hash or Array in the database field!

    Exp.new(:skill => ['Cooking', 'Singing', 'Dancing'])
    
like image 56
Rajesh Kolappakam Avatar answered Oct 14 '25 14:10

Rajesh Kolappakam


You can do it using a serialized list in a single column (comma-separated), but a really bad idea, read these answers for reasoning:

  • Is storing a delimited list in a database column really that bad?
  • How to store a list in a column of a database table

I suggest changing your schema to have a one to many relationship between users and skills.

like image 30
rails_id Avatar answered Oct 14 '25 15:10

rails_id