crievino crievino - 1 month ago 14
Ruby Question

What's the best way to store checkboxes in a PostGres database

what would be the best way to store a student's vehicle in a database?
They can select bike, scooter or car.

Some say the best way is to store a hash in the database (what would the attribute type be?) other say the best way is to create a Has many :through association.

Thanks!

Answer

If the vehicles themselves won't have any data and you're using Postgres 9.2 or newer then I'd recommend storing the vehicles in an array in a vehicle column on the student table. If the vehicles may ever have information about themselves such as how many wheels they have, top speed, weight etc. then you'd be far better off creating a vehicle table with a belongs_to/has_many :through relationship with students.

Update: If you want to add a column that accepts arrays to your students table for holding vehicles you can do the following migration:

 def change
   add_column :students, :vehicles, :string, array: true, default: []
 end
Comments