Completing Your Program
Optional NodeOverview of Your Program
You created a simple program that lets people create and read products from command line. You learned about Ruby while building a program that's like a mini-version of Ruby on Rails itself.
The Product class you created was used for storing information about products. In your program, each instance of Product was stored in an array. In a Rails application, this information would be stored in an actual database, where no 'objects' exist.
Q: How can a row of data from a database be treated like an Object Instance in Rails?
A: Ruby on Rails provides the ActiveRecord framework so you can treat each row in your database (or "record") like an actual instance.
The Model class you created is like a model class you would create in Ruby on Rails. For example, you could create a model called Product
that would store products in a database. All models in Rails inherit from the Rails class ActiveRecord, which give them their special powers!
The Controller class you created is like a controller in Rails. For example, you could create a ProductsController class in Rails for controlling access to pages that relate to your products. Each page would be represented by a method in your Controller class. All controllers in Rails inherit from the Rails class ApplicationController.
The Router is for mapping URLs to specific controller methods. In Rails, you specify such mappings in the routes.rb file, and Rails automatically takes care of the rest.
Note: some of your controller class could have been in the Router...
Challenge
To complete your program, add a price to your products and a delete/destroy option your controller and model.
There will be 3 kinds of input, for creating, showing and deleting products:
input format | sample input | sample output | action taken |
---|---|---|---|
create Name description price |
create Cow moos 15 |
Product created |
Creates product and adds to database. |
show index |
show 0 |
Cow moos 15 |
Retrieves product from index 0 and prints it |
delete index |
delete 0 |
Product deleted |
Deletes product from index 0 |
Guideline
- Add a
@price
variable to your product. Update theto_s
method of your product so it prints the price after the description. Make sure all the code can handle this change, from taking in input, to your controller and model. - Add a
delete(id)
method to your controller and adestroy(id)
action to your model. When your program receives "delete id" as input, your controller's delete method should call your model's destroy method so it removes the item at indexid
from your products array. (Check the Ruby Array docs to see how to delete something at a specific location.)
If your code is flexible, these changes shouldn't be too hard to implement!
Challenge
Add a price to your product and a delete/destroy action to your controller/model.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.