Example 1 (Part A): Fields and Relationships (Books & Authors App)

EXAMPLE 1: BOOKS & AUTHORS

The Books & Authors example is the simplest of all of the examples: It contains only two tables (books & authors), and two scaffoldings. You will need to go through all of the setup steps in “Getting Started”. 

For this example, we will use --god (or --gd) controllers, which means that they are like admin interfaces: By default, they will be able to create/read/update/delete all records on the tables we are constructing.

Remember, only use Gd controllers when you also have some kind of admin authentication. We will cover that example later; for Example 1, the Books & Authors app here only a demo app so it will allow any user to access both tables (no authentication). Of course, this is a 1-user app (you!) and I'll cover authentication in the next example.

Remember, when you make a new Rails app, be sure to know whether or not you are making a JSBundling app or a CSSBundling app. Hot Glue is agnostic of that decision, but for Hot Glue to work correctly, you must have correctly set up Turbo.

Check out the Getting Started YouTube video for an explanation.


rails new BooksAndAuthors --database=postgresql --javascript=webpack --css=bootstrap

Then go through “Getting Started” steps in the README.


(Somewhere along the way during the setup make sure you rails db:create and rails db:migrate to get your schema started.)



Next, we’ll make two models & migrations using the Rails built-in model generators:

rails generate model Author name:string

Take a look at the 4 files that Rails has created for you:



This is a normal Rails migration that should look familiar. If it doesn’t, take a look at the Rails guide for migrations.

class CreateAuthors < ActiveRecord::Migration[6.1]
  def change
    create_table :authors do |t|
      t.string :name

      t.timestamps
    end
  end
end

All we’re doing is creating a table of Authors who have a name. (The t.timestamps tells Rails to create both an updated_at and created_at timestamp for this table.)

Next run rails db:migrate to create the Authors table.



Before we get to building the scaffolding, let’s keep going and build out our Books table. Take a note that this Books table is just a small pretend part of a demo app. Its purpose is to demonstrate one of each type of field so you can see all the field types in action.

rails generate model Book name:string author_id:integer blurb:string long_description:text cost:float how_many_printed:integer approved_at:datetime release_on:date time_of_day:time selected:boolean genre:enum



Don’t migrate the database again — YET!

We will need to fix the enum field before you can run the migration.


Complete and Continue