Load seed data in Rails 3 Project

耗尽温柔 提交于 2020-01-15 03:40:08

问题


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 weird 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 ?


回答1:


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 >>




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6167165/load-seed-data-in-rails-3-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!