When reading the Active Record, I was wondering if I can create a rake to automatically populate some data into database.
After some research, I have the following code samples.
Suppose I have three tables: blogs, posts and comments.
And I have three prepared yaml files: blogs.yml, posts.yml and comments.yml. They are saved at /#{RAILS_ROOT}/lib/tasks/sample_data/
blogs.yml looks like:
Then the rake file "sample_data.rake" is saved under
/#{RAILS_ROOT}/lib/tasks/.
I use TABLES array to hold the table names.
From table names, I use Inflector's classify function to convert the table names to Model Class names and then use const_get function to get the ActiveRecord Class instance. You can't directly use a string name to refer to the Class instance. So this step is necessary.
Next step is easy, ust YAML.load_file to load each yml files:
Notice that the data is actually a hash like "B1000" => <...>. The <...> is another hash with real data: blog_name => "Xianese's blog", etc. So you have to tranverse the hash then use model_class to create a new instance of the Model object and save it:
That is it! It is pretty simple.
Removing sample data is even simpler. I use ruby's eval method to pass in a class string name and delete all records for each Model.
Here is the final code:
I hope this helps.
Subscribe to:
Post Comments (Atom)
1 comment:
I love it when I look for a simple solution to a simple problem, and actually find a simply answer.
Thanks,
Torey
Post a Comment