Rails Cheat Sheet (most of the commands you will be using)
1. `rails new app-name -T`
a. -T to create without the test framework
2. `rails g model user name age:integer`
a. model is singular
b. Creates migration file and model file
c. `rails db:migrate` to run migration
3. Go to “config/routes” to define routes
a. `resources :users` to define all 7 REST routes (index, show, new, create, edit,
update, delete), or be more specific
b. `rails routes` or `localhost:3000/rails/info/routes` to view routes
4. `rails g controller users index show new edit`
a. controller is plural
b. “Index show new edit” is optional and creates the corresponding view files
c. In controller file,
define
methods/actions
and instance
variables that will be
passed into the
view
5. If you did not create view files when generating the controller, create corresponding
view files in “app/views/books/(index, show, new, or edit).erb”
a. Files must be nested under a folder that is the name of the resources (e.g.,
books)
6. `rails g migration add_restaurant_id_to_reviews restaurant:belongs_to`
a. Creates a migration file that contains code to add the column
7. Other commands:
a. `rails s` to start rails server
b. `rails c` to start console for testing
Rails Forms
Docs:
● `form_with`:
https://api.rubyonrails.org/v5.2.0/classes/ActionView/Helpers/FormHelper.html#metho
d-i-form_with
● Form Builder:
https://api.rubyonrails.org/v5.2.0/classes/ActionView/Helpers/FormBuilder.html
○ `text_field`, `collection_select/select`, and `submit` will be used regularly
Sample form with select:
<%= form_with model: Review.new do |f| %>
<%= f.text_field :content %>
<%= f.collection_select :restaurant_id, Restaurant.all, :id, :name %>
OR <%= f.select :restaurant_id, Restaurant.all.map { |restaurant|
[restaurant.name, restaurant.id] } %>
<%= f.submit %>
<% end %>
● For `edit`, replace “Review.new” above with the instance of the review you want to
edit/update