Model to Controller to View


Collapse Content

The last page demonstrated how the controller can pass information to the view. Usually, the controller gets this information from the model, so let's go ahead and code this connection. (You should already have created the model in Rails Model & Data.)

Making Stuff Available from the Controller

It would be good if we could show a product on the home page. We already created some products in the console, so let's go ahead and display one of them. Our first task will be to add a line to our controller so a product is available in the view.

Model Methods showed a method called newest that gets the newest product from the database. Can you call that method and assign what it returns to a variable called @product? Add this line of code to the home action of your product controller.

The Code

Displaying Stuff in The View

Now that the controller made the newest product available, let's make sure we can access it from the view.

Open up your home page and add the following code to the bottom:

<%= @product.inspect %>

Now reload your home page. You should see your product info displayed on the page:

#<Product id: 10, name: "Cornflakes", description: "Flaked corn cereal", price: 3, created_at: "2015-04-20 20:34:53", updated_at: "2015-04-20 20:34:53", category_id: 1, quantity: 9>

This information is sometimes useful for debugging, but we wouldn't want to show something like that to users! Let's fix the page so it just shows what we want:

<%= @product.name %>
<%= @product.description %>

This will just display the name and description of our product, which we can see when we reload the page. It could still use some formatting. Let's add some simple HTML:

<em>New:</em>
<b><%= @product.name %></b>
<p><%= @product.description %></p>

Now when we reload the page, we can see an actual website taking shape:

MVC

You just created your first page that involves all parts of the Rails.

The Controller calls a method from the Model that returns data from the database. The controller makes this data available to the view by assigning it to a instance variable, marked with a @. The view is an HTML template that shouldn't run any programming logic on its own, but it contains embedded Ruby for displaying information from the controller.

Classic Product

Optional Challenge

Add a "Classic" Product to the home page that displays the oldest product. Show the same information as for the newest product.

See this screencast for help with this page.

Challenge

Run rake test in your terminal.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]