2011-04-01 20 views
0

在部署過程中(到共享主機),我想檢查某些數據是否被存儲在數據庫中,如果沒有我想在部署過程中,以將其插入。任何人都知道如何去做我所描述的?如何在部署期間播種數據?

+0

您檢查了Rails遷移指南:http://guides.rubyonrails.org/migrations.html – 2011-04-01 21:05:36

+0

@Mladen Jablanovic:是的,我已經簽出的指南;問題是我沒有ssh訪問,因此我無法運行'rake'命令。 – DanMark 2011-04-05 16:46:52

回答

0

我個人喜歡用燈具來填充我的數據庫,無論是測試或沒有。一旦你創建了它們,你可以創建一個rake任務來重置你的db並填充它。我有這個reset_db.rake任務:

namespace :db do 
    desc "Drop, create, migrate, seed the database and prepare the test database for rspec" 
    task :reset_db => :environment do 
    Rake::Task['db:drop'].invoke 
    Rake::Task['db:create'].invoke 
    Rake::Task['db:migrate'].invoke 
    Rake::Task['db:fixtures:load'].invoke 
    Rake::Task['db:test:prepare'].invoke 
    end 
end 

在我的/ lib/tasks文件夾中。我用「rake db:reset_db」執行它。

+0

那就是用自己的預期目的外燈具一個非常糟糕的主意,如果他們是有用的存在,而不是工廠 – Wes 2011-04-01 21:23:12

+0

好了,大衛Hannson,Rails的創造者,似乎不同意這是更值得商榷。我也很好,對不起。 – Spyros 2011-04-01 23:20:05

0

我不知道你有多麼的靈活性與您對其他數據庫(不知道你是否能創造只爲這些值另一個數據庫)的主機,但你可以在XML文檔中放置這些數據,然後有一個如果腳本不存在,則插入這些值。

+0

當你有權訪問Rails和Rake數據庫時:爲什麼你會這樣做? – Wes 2011-04-01 21:24:18

0

--- DB SEED APPROACH ---

有一個在db目錄(稱爲seed.rb文件APP_ROOT/db/seeds.rb),您可以在其中添加種子數據。註釋說明可在文件中找到(複製如下)。

# This file should contain all the record creation needed to seed the database with its default values. 
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). 
# 
# Examples: 
# 
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) 
# Mayor.create(name: 'Emanuel', city: cities.first) 

你可以用你想添加例如記錄填寫:

Users.create(
      :email=>"dummy", :pwd_hash=>"3x35zbb2...", 
      :pwd_salt=>'423x', :admin=>true 
) 

...然後運行耙分貝:種子的記錄添加到您的表。

--- 編輯遷移方法 ---

最簡單的選擇(儘管DB:種子可能是更好的)是剛剛與種子數據運行遷移。只需要這樣做。需要具有管理員權限的種子用戶,因爲網站沒有註冊選項。遷移文件如下:

class CreateUsers < ActiveRecord::Migration 
    def change 
    create_table :users do |t| 
     t.string :email 
     t.string :password 
     t.string :name 
     t.boolean :admin 
     t.integer :company_id 

     t.timestamps 
    end 

    #create the seed user with admin priviledges 
    User.create!(:email=>"[email protected]", :password=>"test", :name=>"Dummy", :admin=>true, :company_id=>0) 

    end 
end 
相關問題