Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default data in a table in rails?

I have a table that I'm going to store units of measurements in and the corresponding category. For example, "cups, volume" and "ounce, mass". I only have about 12 measurements I care about, and I want them to be in the database without manually entering them because anytime I want to deploy it or move the code somewhere, I want this to recreate.

So, I figure the best way to do this is to create a csv file with them, and then use rake db:seed. But I've never done this before so can someone guide me as to how to create this csv, and how to write the seeds.rb file to generate that? Is this the right way to do it?


SOLUTION:

#db/seeds.rb
require 'open-uri'

#Supply all the units of measurement to be used
Unit.delete_all
open("db/seeds/measurements.csv") do |measurements|
  measurements.read.each_line do |measurement|
    unit, uof = measurement.chomp.split(",")
    Unit.create!(:name => unit, :unit_of => uof)
  end
end
like image 445
GiH Avatar asked Dec 18 '25 20:12

GiH


2 Answers

Just write the code you'd use to generate them manually and put it in the seeds.rb. You can use normal ruby in that file; so either just write plain create's or load a csv you store in, e.g. db/seeds/measurements.csv. To get the path to that file, use Rails.root.join("db/seeds/measurements.csv").

Example:

File.open(Rails.root.join("db/seeds/measurements.csv")) do |f|
  # use f here
end
like image 144
Femaref Avatar answered Dec 21 '25 12:12

Femaref


There's a file called seeds.rb in db directory.

You can add your default data in it and when you execute rake db:seed, that data will be populated in your database.

Here's an example of how you can add seeds to it.

product_types = ProductType.create([
                                   {:name => 'clock',:organisation_id => 1}
])
like image 20
VivekVarade123 Avatar answered Dec 21 '25 10:12

VivekVarade123