开发者

Load seed data in Rails 3 Project

Till now, i have been using Fixtures, along with a rake task to create some seed data for my database. This worked well, but i suddenly have wei开发者_StackOverflow中文版rd problems(like getting autogen ids of 1,2,3.. in a model and then wrong ids in the join model, making the association not work at all).

Thus, i was wondering what a better alternative is. I've read about different things, as well as the railscast on seeding data.

My data does not really share same pieces of information. It's like separate entries that have to be inserted as they are. For instance, think that i have to insert 1000 users that have particular abilities and skills. This needs some join models and some neat handling of the associations like fixtures do.

So, is there a better than fixtures way to accomplish that ?


Here are three different options which I use all the time. Let me know what you think and how you get on. All the best.

Github Gist >>


Rails 3 provides some basic seeding capabilities. See: http://ryandaigle.com/articles/2009/5/13/what-s-new-in-edge-rails-database-seeding

To summarise:

  • You can put any seeding code (in Ruby, using your AR models) in db/seeds.rb
  • Then run rake db:seed to load this (rake db:setup does this automatically)

In my seeds file I tend to wrap everything in a transaction, and also define IDs manually (with the assumption that there is no existing data in the DB). Hat tip to the Prologue gem. Example:

ActiveRecord::Base.transaction do
  if User.count == 0 && Role.count == 0
    user = User.new :name => "Admin", :email => "admin@example.org", :password => "password", :password_confirmation => "password"
    user.id = 1
    user.save!
    user.confirmed_at = user.confirmation_sent_at
    user.save!

    role1 = Role.new :name => 'Admin'
    role1.id = 1
    role1.save!

    role2 = Role.new :name => 'Member'
    role2.id = 2
    role2.save!

    user.role_ids = [1,2]
    user.save!
  end
end

There may be better ways of doing this!

In your case you could load up data from a CSV file or something and create the model objects programmatically.


Fixed ID maybe useful for those default data in database. in @jits case, he doesn't want the ID and the role permission messed up, the IDs are required to be fixed and maintained constantly over several environment or setups.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜