Making a Basic Rails Website with RESTful Actions
I chose to make a very simple website based on Food and Nutrients as models. For this example, let’s say for simplicity that a nutrient belongs to food and a food has many nutrients. Start your application in the terminal with rails new (name of your project). Let’s build our models. In the terminal, type rails g model Food name:string. This will set up your food model and table. Then type rails g model Nutrient name: string food_id: integer. This will set up your nutrient model and connect it to the food model. Run rails db:migrate to create your tabels. They should look like this:


You can then go into your model files and set up Food has_many :nutrients and Nutrient belongs_to :food.
5 of our RESTful actions will be written in nutrients_controller.rb. The edit and update actions will be written in foods_controller.rb. The first thing we should do is write our routes because this is how the server works.

Now let’s go into our controllers and start building our RESTful actions.

Index will follow this format:

and will be found at the local host server/nutrients.
Show:

/nutrients/:id
(:id being 1, 2, etc..)
It will look like this once we set up the HTML.

New:

/nutrients/new
It will look like this once we set up the HTML. We will make a form_for to have a drop down list of foods to associate with our new nutrient.

Create:

This creates an actual row in our database, holding information about the nutrient submitted with the new form.
Destroy:

The button for this can be where you want it, but we will put it in the show page.
We also have to write strong params for both nutrient and food so that we can use the form_for.

In foods_controller.rb, we want to have index and show, but we also want to use edit and update here.
Edit:

found at /foods/:id/edit.
Update:

This makes sure that what you edit is valid and saved.
Now that our controllers are done, we need to write the view pages. Because we are making new nutrients, we need the index.html.erb, show.html.erb, and new.html.erb.
For the nutrients index:

This will show the list of nutrients on the screen.
To make a new nutrient:

To show the nutrient once it’s clicked on and offer a delete button:

This will also show what food the nutrient is found in.
The index page for food will look the same as the index page for nutrient, except that the word nutrients/nutrient will be replaced by foods/food.
The show page will show the food with the clickable list of nutrients underneath.


Food’s edit.html.erb page looks like this:

and will render this:

with a dropdown of nutrients that you can add to edit and update the food.
Now that your models are set, you can play around with this, set up validations to make sure that the user enters something along the guidelines you want, and add CSS and images to make it look interesting!
