Skip to content

Instantly share code, notes, and snippets.

@progapandist
Created November 10, 2020 17:16
Show Gist options
  • Save progapandist/1282e1c0c3d4eccc58d965454cc84e69 to your computer and use it in GitHub Desktop.
Save progapandist/1282e1c0c3d4eccc58d965454cc84e69 to your computer and use it in GitHub Desktop.
class CreatePets < ActiveRecord::Migration[6.0]
def change
create_table :pets do |t|
t.string :address
t.string :species
t.date :found_on
t.timestamps
end
end
end
class AddAddressToPets < ActiveRecord::Migration[6.0]
def change
add_column :pets, :name, :string
end
end
<%= form_for(animal) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<br>
<%= f.label :address %>
<%= f.text_field :address %>
<br>
<%= f.label :species %>
<%= f.collection_select :species, Pet::SPECIES, :to_s, :to_s %>
<br>
<%= f.label :found_on %>
<%= f.date_select :found_on %>
<br>
<%= f.submit %>
<% end %>
class ApplicationController < ActionController::Base
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
<%= render "form", animal: @pet %>
<ul>
<% @pets.each do |pet| %>
<li>
<%= link_to pet.name, pet_path(pet) %>
<% if pet.species == "dog" %>
| 🐶
<% elsif pet.species == "cat" %>
| 😸
<% end %>
<% if pet.found_on && pet.address %>
| <%= pet.found_on %> at <%= pet.address %>
<% end %>
| <%= link_to "👨‍👩‍👦", pet_path(pet), method: :delete %>
</li>
<% end %>
</ul>
<%= render "form", animal: @pet %>
class Pet < ApplicationRecord
SPECIES = ["dog", "cat", "bird", "dolphin"]
validates :name, presence: true
validates :species, inclusion: { in: SPECIES }
end
class PetsController < ApplicationController
before_action :set_pet, only: [:show, :edit, :update, :destroy]
def index
@pets = Pet.all
end
def show
end
def new
@pet = Pet.new
end
def create
@pet = Pet.new(pet_params)
@pet.save
redirect_to root_path
end
def edit
end
def update
@pet.update(pet_params)
redirect_to pet_path(@pet)
end
def destroy
@pet.destroy
redirect_to root_path
end
private
def set_pet
@pet = Pet.find(params["id"])
end
def pet_params
params.require(:pet).permit(:name, :species, :address, :found_on)
end
end
Rails.application.routes.draw do
root to: "pets#index"
resources :pets
end
<h2> <%= @pet.name %> </h2>
<% if @pet.species == "dog" %>
🐶
<% end %>
<% if @pet.found_on && @pet.address %>
<%= @pet.found_on %> at <%= @pet.address %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment