Scaffolding Demo with Rails 7 and Bootstrap === Generate basic stuff with scaffold --- ```sh rails new demo && cd demo rails g scaffold Group name:string github_org:string rails g scaffold Student buckid:integer fname:string lname:string group:references rails db:migrate ``` It's a working web app! Run `rails server`. Poke around the files: * Student model already has association, but Group does not * Add `has_many :students` to Group model * See controller, views, routes Create groups in rails console (and/or in browser) ```ruby > Group.create name: "Blue Jackets", github_org: "arena-district" > Group.create name: "Columbus Crew", github_org: "mls-cmh" ``` Create students (see error message when group does not exist…) ```ruby > Student.create buckid: 32423, fname: "Primo", group_id: 1 > Student.create buckid: 32451, fname: "Cher", group: Group.first # alternative, provide group obj instead of id > Student.create buckid: 44222, lname: "Pantani" # seems to pass, but doen't (returns nil) > Student.create! buckid:4545, lname: "Pantani", group: Group.last ``` Change landing page by adding a route ```ruby # config/routes.rb root to: 'students#index' ``` Improve `students#show` view --- Better headers for fields Show group name instead of id (or just group blob): in `_student.html.erb` partial (`app/views/students/_student.html.erb`): ```erb <%# the following are possible alternatives for what to show %> <%= student.group_id %> <%= student.group %> <%= student.group.id %> <%= student.group.name %> ``` Link to group instead of just showing info: ```erb <%= link_to student.group.name, student.group %> ``` Add links from `groups#index` and `students#index` to the other listing: ```erb <%# in app/views/students/index.html.erb %> <%= link_to 'List Groups', groups_path %> <%# in app/views/groups/index.html.erb %> <%= link_to 'List Students', students_path %> ``` Improve `students#_form` partial --- Add a pull-down for entering group info: ```erb <%# in app/views/students/_form.html.erb %> <%= form.collection_select :group_id, Group.all, :id, :name %> <%# alternative: sorts groups alphabetically %> <%= form.collection_select :group_id, Group.order(:name), :id, :name %> ``` Validations --- Add to Student model: ```ruby # app/models/student.rb validates :buckid, uniqueness: true, presence: true validates :lname, presence: true ``` Styling with Bootstrap (Best to do this at app creation time!!) --- See [https://bootrails.com/blog/rails-7-bootstrap-5-tutorial/](https://bootrails.com/blog/rails-7-bootstrap-5-tutorial/) ```sh # if yarn is not yet installed, enable corepack: corepack enable rails new demo --css=bootstrap ``` Add the bootstrap styling --- _e.g._ change `groups#index` view: ```erb <%# in app/views/groups/index.html.erb %> <%= link_to "Show this group", group, class: 'btn btn-secondary' %> ... <%= link_to "New group", new_group_path, class: 'btn btn-primary' %> ``` change `groups#_group` partial: ```erb <%# in app/views/groups/_group.html.erb %>