There are many tasks that need to be performed outside of your website that are related to your web application. An example would be cleaning up temporary files. You wouldn’t want to have this code running in a web page. Fortunately rails includes a mechanism for doing this. Rake tasks make it easy to automate various aspects of your application.
First, we need to create a couple models for our sample. In this sample we will have 2 models. Our first model, Product, will store product information. Our second model, Review, will be a review of the product. Run the commands below to generate these 2 models:
1 2 3
Next, we need some seed data. Open up your seeds.rb file and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Then run rake db:seed
Now, lets open up the Product model so that we can add an association to reviews. Modify the Product model so that it looks like the code listed below:
1 2 3
Then create a file called calculate_averages.rake in the lib/tasks folder and add the following code:
1 2 3 4 5 6 7 8 9 10
Now, if we run our rake command we will see that the averages are updated in the database.
So far so good, That’s it!!! See ya!!! :)