4

I'm having some difficulties understanding how to use the seed.rb script in rails.

So far, I've used it to populate my database every time i deploy my application.

Like this.

seed.rb

["Video", "Tv"].each do |thing|
  Category.create(name: thing)
end

category.rb

class Category < ActiveRecord::Base
  validates_uniqueness_of :name
end

The script can now be runned every deploy or pull. Anyone in the dev team can now add their own category without have to worry about duplications.

Like this.

Person one

  • Adding the Table category to seed.rb.
  • Commit and push to master.

Person two

  • Pull master.
  • Run rake db:migrate and rake db:seed to ensure that the local database is up-to-date.
  • Deploy application to production server. rake db:seed is being runned on the server to ensure an up-to-date database.

Is this workflow okay, if not, where should I put the new data to ensure that every developer has an up-to-date database?

Jesper
  • 4,535
  • 2
  • 22
  • 34
Linus Oleander
  • 17,746
  • 15
  • 69
  • 102

1 Answers1

5

I would recommend writing your seed so that it can be run more than once without trying to create duplicate categories...

["Video", "Tv"].each do |thing|
  Category.find_or_create_by_name(thing)
end
Paul Sturgess
  • 3,254
  • 2
  • 23
  • 22
  • Using one field was just an example. I could for example have a `active` filed in the table. The `active` field might change during runtime, which means that running `Category.find_or_create_by_name_and_active(name, active)` might create duplications. – Linus Oleander Apr 19 '11 at 21:26
  • 1
    If the unique attribute is `name` then you do... `["Video", "Tv"].each do |name| category = Category.find_or_initialize_by_name(name) category.update_attributes(...) end` – Paul Sturgess Apr 20 '11 at 10:21