Skip to content

Instantly share code, notes, and snippets.

@caioertai
Created May 20, 2022 23:15
Show Gist options
  • Save caioertai/3fe8500ba9a85a0a2295cf1f905af65d to your computer and use it in GitHub Desktop.
Save caioertai/3fe8500ba9a85a0a2295cf1f905af65d to your computer and use it in GitHub Desktop.

Rails Quiz - 879

1. How do you create a Rails app?

rails new <APP_NAME> 

2. How do you start coding a Rails project? Give the right sequence.

  1. Coding the views
  2. Coding the controllers
  3. Coding the models

3 - 2 - 1

3. How do you generate a Song model with a title and a year ?

rails g model Song title:string year:integer
rails g model ModelName column_name:column_type column2_name:column2_type

4. What are the 2 created files?

app/models/song.rb                 # model
db/migrate/XXXXXXX_create_songs.rb # migration

5. What is the rails command you should type then?

rails db:migrate # Runs all pending (down) migration

6. How do you add a category (ex: “rock” , “electro” , etc..) to your songs table using the correct Rails generator?

rails g migration add_category_to_songs category:string

7. What is the created file?

db/migrate/XXXXXXX_add_category_to_songs.rb # migration
class AddCategoryToSongs < ActiveRecord::Migration[6.1]
  def change
    add_column :songs, :category, :string
  end
end

8. What is the rails command you should type again?

rails db:migrate # Runs all pending (down) migration

9. Add a validation on the presence of a song title in the models/song.rb file

class Song < ApplicationRecord
  # validates(:title, { presence: true })
  # validates(:title, presence: true)
  validates :title, presence: true
end

10. Now crash-test your model’s validation:

sail_away = Song.new(title: "")
sail_away.valid? # sail_away.save # => false
sail_away.title = "Sail Away"
sail_away.valid? # sail_away.save # => true

11. What is the Rails flow you need to follow again and again? Give the correct order.

  1. The Router is routing the HTTP request to controller#action.
  2. The action is getting data from models.
  3. Everything starts with an HTTP Request.
  4. The action is rendering the view.

3 - 1 - 2 - 4

12. What are the 4 different parts inside an HTTP request?

VERB    # GET / POST / PATCH / PUT /DELETE
URL     # google.com
--------- below the surface
HEADERS # Filled by the client/browser
BODY    # Optional. Has the data from forms or others...

13. Are the HTTP requests in the config/routes.rb associated with their 2 routes the same? Why?

GET /posts
POST /posts

No. The verb is different.

14. What’s the difference between a GET and a POST request?

GET intends to request information about a resource. POST for sending info about a resource. POST should have a body of data.

15. Complete the controller code using the correct params key.

HTTP request: GET /search?query=thriller Routing in config/routes.rb: get "/search" => "songs#search"

class SongsController < ApplicationController
  # GET /search?query=thriller
  # params => { query: "thriller" }
  # params[:query] => "thriller"
  def search
    @songs = Song.where("title ILIKE '%?%'", params[:query])
  end
end

16. Complete the controller code using the correct params key.

HTTP request: GET /songs/named/thriller Routing in config/routes.rb: get "/songs/named/:name" => "songs#search"

class SongsController < ApplicationController
  # GET /songs/named/sail
  # GET /songs/named/thriller
  # GET /songs/named/:name
  # params => { name: "thriller" }
  def search
    @songs = Song.where("title ILIKE '%?%'", params[:name])
  end
end

17. What are the 7 CRUD routes generated by the resources method resources :songs in Rails?

VERB PATH CONTROLLER ACTION
GET /songs songs index
GET /songs/:id songs show
GET /songs/new songs new
POST /songs songs create
GET /songs/:id/edit songs edit
PATCH/PUT /songs/:id songs update
DELETE /songs/:id songs destroy

18. How do you print your routes and their URL prefix helpers?

rails routes

rails routes -g=songs

19. How do you generate a controller for your songs?

rails g controller Songs

20. Implement the Read actions in your songs controller.

class SongsController < ApplicationController
  def index
    @songs = Song.all
  end
    
  # GET songs/:id
  def show
    @song = Song.find(params[:id])
  end
end

21. What are the 2 requests needed to create a new song? Implement the songs#new and songs#create actions

class SongsController < ApplicationController
  def new
    @song = Song.new
  end
    
  def create
    @song = Song.new(song_params)
      
    if @song.save
      redirect_to songs_path # song_path(@song)
    else
      render :new
    end
  end
    
  private
    
  def song_params
    params.require(:song).permit(:title, :year)
  end
end

22. Why do we have to filter parameters using “strong params” in the controller?

To avoid code unwanted code execution. Users could add form fields otherwise, which could trigger unintended writers in the model.

23. Hard question: What is the HTML generated? Fill in the blanks:

Imagine that: @song = Song.new

Now what is the HTML code generated by:

<%= form_for @song do |f| %>
  <%= f.text_field :title %>
  <%= f.submit %>
<% end %>
<!--- VERB                 PATH --->
<form method="post" action="/songs">
  <input type="text" name="song[title]" value= "">
</form>

24. Hard question: What is the HTML generated? Fill in the blanks.

Imagine that: @song #=> <#Song: id: 18, title: "Hey jude", year: 1968, category: "rock">

Now what is the HTML code generated by: <%= form_for @song do |f| %> <%= f.text_field :title %> <%= f.submit %> <% end %>

<!---        VERB           PATH --->
<form method="patch" action="/songs/18">
  <input type="text" name="song[title]" value= "Hey jude">
</form>

25. Now you want to add reviews to your app. Here are some constraints.

rails g model Review content:string song:references

26. Run the migration.

rails db:migrate

27. Add validations & associations.

class Review < ApplicationRecord
  validates :content, presence: true
  belongs_to :song
end

class Song < ApplicationRecord
  has_many :reviews
end

28. Generate the reviews controller.

rails g controller Reviews

29. Add the necessary routes (we don’t want the 7 CRUD actions for reviews)

resources :songs
  resources :reviews, only: [:new, :create]
end

30. Now code your controller.

class SongsController < ApplicationController
  def new
    @song = Song.find(params[:song_id])
    @review = Review.new
  end

  def create
    @song = Song.find(params[:song_id])
    @review = Review.new(review_params)
    @review.song = @song

    if @review.save
      redirect_to @song
    else
      render :new
    end
  end

  private

  def review_params
    params.require(:review).permit(:content)
  end
end

31. step 3: views. Add a song’s reviews on its show page:

<h1><%= @song.title %></h1>


<% @song.reviews.each do |review| %>
	<div class="class">
        <%= review.content %>
	</div>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment