Data in Views

Let's recap the major things we've done up to this point in the course

  • We've learned to use the basic tools, like Git, the Linux command-line interface, and a code editor environment
  • We've learned to query and manipulate data using SQL
  • We've learned the basics of the Ruby programming language
  • We've learned how to use Ruby to query and manipulate data, instead of using SQL
  • We've created a basic web app that dynamically changes content with each page load

Now it's time to put all of these tools to work at the same time, and create a web application that talks to the data in our database!

Begin by creating a Company and Contacts model and corresponding database tables:

rails generate model Company
rails generate model Contact

That will create migration files; in them:

class CreateCompanies < ActiveRecord::Migration[7.0]
  def change
    create_table :companies do |t|
      t.string "name"
      t.string "city"
      t.string "state"
      t.timestamps
    end
  end
end
class CreateContacts < ActiveRecord::Migration[7.0]
  def change
    create_table :contacts do |t|
      t.string "first_name"
      t.string "last_name"
      t.string "email"
      t.string "phone_number"
      t.integer "company_id"
      t.timestamps
    end
  end
end

Then:

rails db:migrate

Next, if you look at scripts/create_data.rb you'll find a simple script to create three companies and four contacts. Run the script by executing:

rails runner scripts/create_data.rb

Next, configure a resource for companies...

Rails.application.routes.draw do
  resources "tacos"
  resources "companies"
end

...and create a controller for companies. Note that the controller name is pluralized.

rails generate controller companies

Finally, create a view for companies:

<% companies = Company.all %>
<h1>Companies</h1>
<ul>
  <% for company in companies %>
    <li><%= company["name"] %> – <%= company["city"] %>, <%= company["state"] %></li>
  <% end %>
</ul>
app/views/companies/index.html.erb

Try it!

Create a resource, controller, and "index" view for contacts, showing all contacts with contact information and the name of the company for each contact.