Giter VIP home page Giter VIP logo

sinatra-complex-forms-associations's Introduction

Sinatra and Active Record: Associations and Complex Forms

Objectives

  • Build forms that allow a user to create and edit a given resource and its associated resources.
  • Build controller actions that handle the requests sent by such forms.

Introduction

As the relationships we build between our models grow and become more complex, we need to build ways for our users to interact with those models in all of their complexity. If a genre has many songs, then a user should be able to create a new song and select from a list of existing genres and/or create a new genre to be associated with that song, all at the same time. In other words, if our models are associated in a certain way, our users should be able to create and edit instances of those models in ways that reflect those associations.

In order to achieve this, we'll have to build forms that allow for a user to create and edit not just the given object but any and all objects that are associated with it.

Overview

This is a walk-through with some extra challenges for you to complete on your own. There are tests, so be sure to run the tests to make sure you're following along correctly. To follow along, use shotgun to start your app and visit URLs/fill out forms as instructed. In this walk-through, we're dealing with a pet domain model. We have an Owner model and a Pet model. An owner has many pets, and a pet belongs to an owner. We've already built the migrations, models, and some controller actions and views. Fork and clone this lab to follow along.

Because an owner can have many pets, we want to be able to choose which of the existing pets in our database to associate to a new owner when the owner is being created. We also want to be able to create a new pet and associate it with the owner being created. So, our form for a new owner must contain a way to select a number of existing pets to associate with that owner as well as a way to create a brand new pet to associate with that owner. The same is true of editing a given owner: we should be able to select and deselect existing pets and/or create a new pet to associate with the owner.

Here, we'll be taking a look together at the code that will implement this functionality. Then, you'll build out the same feature for creating/editing new pets.

Instructions

Before You Begin

Since we've provided you with much of the code for this project, take a few moments to go through the provided files and familiarize yourself with the app. Note that an owner has a name and has many pets and a pet has a name and belongs to an owner. Note that we have two separate controllers, one for pets and one for owners, each of which inherit from the main application controller. Note that each controller has a set of routes that enable the basic CRUD actions (except for delete –– we don't really care about deleting for the purposes of this exercise).

Make sure you run rake db:migrate and rake db:seed before you move on. This will migrate our database and seed it with one owner and two pets to get us started.

A Note on Seed Files

The phrase 'seeding the database' refers to the practice of filling up your database with some dummy data. As we develop our apps, it is essential that we have some data to work with. Otherwise, we won't be able to tell if our app is working or try out the actions and features that we are building. Sinatra makes it easy for us to seed our database by providing us with something called a seed file. This file should be placed in the db directory, db/seeds.rb. The seed file is where you can write code that creates and saves instances of your models.

When you run the seed task provided by Sinatra and Rake, rake db:seed, the code in the seed file will be executed, inserting some sample data into your database.

Go ahead and open up the seed file in this app, db/seeds.rb. You should see the following:

# Add seed data here. Seed your database with `rake db:seed`
sophie = Owner.create(name: "Sophie")
Pet.create(name: "Maddy", owner: sophie)
Pet.create(name: "Nona", owner: sophie)

This is code you should be pretty familiar with by now. We are simply creating and saving an instance of our Owner class and creating and saving two new instances of the Pet class.

So, when rake db:seed is run, the code in this file is actually executed, inserting the data regarding Sophie, Maddy, and Nona into our database.

You can write code to seed your database in any number of ways. We've done it fairly simply here, but you could imagine writing code in your seed file that sends a request to an external API and instantiates and saves instances of a class using the response from the API. You could also write code that opens a directory of files and uses information about each file to create and save instances of a class. The list goes on.

Creating a New Owner and Their Associated Pets

Open up app/views/owners/new.erb and you should see the following code:

<h1>Create a new Owner</h1>

<form action="/owners" method="POST">
  <label>Name:</label>

  <br>

  <input type="text" name="owner[name]" id="owner_name">

  <input type="submit" value="Create Owner">
</form>

Here we have a basic form for a new owner with a field for that new owner's name. However, we want our users to be able to create an owner and select existing pets to associate with that new owner at the same time. So, our form should include a list of checkboxes, one for each existing pet, for our user to select from at will.

How can we dynamically, or programmatically, generate a list of checkboxes for all of the pets that are currently in our database?

Dynamically Generating Checkboxes

In order to dynamically generate these checkboxes, we need to load up all of the pets from the database. Then, we can iterate over them in our owners/new.erb view using ERB tags to inject each pet's information into a checkbox form element. Let's take a look:

# controllers/owners_controller.rb
get '/owners/new' do
  @pets = Pet.all
  erb :'/owners/new'
end
# views/owners/new.erb
<% @pets.each do |pet| %>
  <input type="checkbox" name="owner[pet_ids][]" id="<%= pet.id %>" value="<%= pet.id %>"><%= pet.name %><br>
<% end %>

Let's break this down:

  • We use ERB to get all of the pets with Pet.all, then we iterate over that collection of Pet objects and generate a checkbox for each pet.

  • That checkbox has a name of "owner[pet_ids][]" because we want to structure our params hash such that the array of pet IDs is stored inside the "owner" hash. We are aiming to associate the pets that have these IDs with the new owner.

  • We give the checkbox a value of the given pet's ID. This way, when that checkbox is selected, its value, i.e., the pet's ID, is what gets sent through to the params hash.

  • We give the checkbox an id of the given pet's ID so that our Capybara test can find the checkbox using the pet's ID.

  • Finally, in between the opening and closing input tags, we use ERB to render the given pet's name.

The result is a form that looks something like this:

Let's place a binding.pry in the post '/owners' route and submit our form so that we can get a better understanding of the params hash we're creating with our form. Once you hit your binding, type params in the terminal, and you should see something like this:

{"owner"=>{"name"=>"Adele", "pet_ids"=>["1", "2"]}}

I filled out my form with a name of "Adele", and I checked the boxes for "Maddy" and "Nona". So, our params hash has a key of "owner" that points to a value that is a hash containing two keys: "name", with a value of the name entered into the form, and "pet_ids", with a value of an array containing the ids of all of the pets we selected via our checkboxes. Let's move on to writing the code that will create a new owner and associate it to these pets.

Creating New Owners with Associated Pets in the Controller

We are familiar with using mass assignment to create new instances of a class with Active Record. For example, if we had a hash, owner_info, that looked like this...

owner_info = {name: "Adele"}

...we could easily create a new owner like this:

Owner.create(owner_info)

But our params hash contains this additional key of "pet_ids" pointing to an array of pet ID numbers. You may be wondering if we can still use mass assignment here. Well, the answer is yes. Active Record is smart enough to take that key of pet_ids, pointing to an array of numbers, find the pets that have those IDs, and associate them to the given owner, all because we set up our associations such that an owner has many pets. Wow! Let's give it a shot. Still in your Pry console that you entered via the binding.pry in the post '/owners' action of the OwnersController, type:

@owner = Owner.create(params["owner"])
# => #<Owner:0x007fdfcc96e430 id: 2, name: "Adele">

It worked! Now, type:

@owner.pets
#=> [#<Pet:0x007fb371bc22b8 id: 1, name: "Maddy", owner_id: 2>, #<Pet:0x007fb371bc1f98 id: 2, name: "Nona", owner_id: 2>]

And our usage of mass assignment successfully associated the new owner with the pets whose ID numbers were in the params hash!

Now that we have this working code, let's go ahead and place it in our post '/owners' action:

# app/controllers/owners_controller.rb

post '/owners' do
  @owner = Owner.create(params[:owner])
  redirect "/owners/#{@owner.id}"
end

Great! We're almost done with this feature. But, remember that we want a user to be able to create a new owner, select some existing pets to associate with that owner, and also have the option of creating a new pet to associate with that owner. Let's build that latter capability into our form.

Creating a New Owner and Associating Them with a New Pet

This will be fairly simple. All we need to do is add a section to our form for creating a new pet:

and/or, create a new pet:
    <br>
    <label>name:</label>
      <input  type="text" name="pet[name]"></input>
    <br>

Now our whole form should look something like this:

<h1>Create a New Owner</h1>

<form action="/owners" method="POST">
  <label>Owner Name:</label>
  <br>
  <input type="text" name="owner[name]">

  <br>
  <p>Select an existing pet or create a new one below.</p>


  <h3>Existing Pets</h3>
  <% @pets.each do |pet| %>
    <input type="checkbox" name="owner[pet_ids][]" id="<%= pet.id %>" value="<%= pet.id %>"><%= pet.name %></input><br>
  <% end %>
  <br>

  <h3>New Pet</h3>
  <label>Pet Name: </label>
  <br>
  <input type="text" name="pet[name]" id="pet_name"></input>
  <br><br>

  <input type="submit" value="Create Owner">
</form>

Note that we've included the section for creating a new pet at the bottom of the form and we've given that input field a name of pet[name]. Now, if we fill out our form like this...

...when we submit our form, our params hash should look something like this:

{"owner"=>{"name"=>"Adele", "pet_ids"=>["1", "2"]}, "pet"=>{"name"=>"Fake Pet"}}

Our params["owner"] hash is unchanged, so @owner = Owner.create(params["owner"]) still works. But what about creating our new pet with a name of "Fake Pet" and associating it to our new owner?

For this, we'll have to grab the new pet's name from params["pet"]["name"], use it to create a new pet, and add the new pet to our new owner's collection of pets:

@owner.pets << Pet.create(name: params["pet"]["name"])

But, you might be wondering, what if the user does not fill out the field to name and create a new pet? In that case, our params hash would look like this:

{"owner"=>{"name"=>"Adele", "pet_ids"=>["1", "2"]}, "pet"=>{"name"=>""}}

The above line of code would create a new pet with a name of an empty string and associate it to our owner. That's no good. We'll need a way to control whether or not the above line of code runs. Let's create an if statement to check whether or not the value of params["pet"]["name"] is an empty string.

if !params["pet"]["name"].empty?
  @owner.pets << Pet.create(name: params["pet"]["name"])
end

That looks pretty good. Let's put it all together:

post '/owners' do
  @owner = Owner.create(params[:owner])
  if !params["pet"]["name"].empty?
    @owner.pets << Pet.create(name: params["pet"]["name"])
  end
  redirect "owners/#{@owner.id}"
end

NOTE: When using the shovel operator, ActiveRecord instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record.

Let's sum up before we move on. We:

  • Built a form that dynamically generates checkboxes for each of the existing pets.

  • Added a field to that form in which a user can fill out the name for a brand new pet.

  • Built a controller action that uses mass assignment to create a new owner and associate it to any existing pets that the user selected via checkboxes.

  • Added to that controller action code that checks to see if a user did in fact fill out the form field to name and create a new pet. If so, our code will create that new pet and add it to the newly-created owner's collection of pets.

Now that we can create a new owner with associated pets, let's build out the feature for editing that owner and their associated pets.

Editing Owners and Associated Pets

Our edit form will be very similar to our create form. We want a user to be able to edit everything about an owner: the owner's name, any existing pet associations, and any new pet the user would like to create and associate with that owner. So, our form should have the standard, pre-filled name field as well as dynamically generated checkboxes for existing pets. This time, though, the checkboxes should be automatically checked if the given owner already owns that pet. Finally, we'll need the same form field we built earlier for a user to create a new pet to be associated with our owner.

Let's do it!

# edit.erb
<h1>Update Owner</h1>

<h2>Edits for <%= @owner.name %></h2>

  <form action="/owners/<%= @owner.id %>" method="POST">
    <input id="hidden" type="hidden" name="_method" value="patch">
    <label>Edit the Owner's Name:</label>
    <br>
    <input type="text" name="owner[name]" value="<%= @owner.name %>">

    <br>
    <p>Select an existing pet or create a new one below.</p>


    <h3>Existing Pets</h3>
    <% @pets.each do |pet| %>
      <input type="checkbox" name="owner[pet_ids][]" id="<%= pet.id %>" value="<%= pet.id %>" <%='checked' if @owner.pets.include?(pet) %>><%= pet.name %></input><br>
    <% end %>
    <br>

    <h3>New Pet</h3>
    <label>Pet Name: </label>
    <br>
    <input type="text" name="pet[name]" id="pet_name"></input>
    <br><br>

    <input type="submit" value="Update Owner">
  </form>

The main difference here is that we added the checked property to each checkbox with a condition to test whether the given pet is already present in the current owner's collection of pets. We implemented this if statement by wrapping the checked attribute in ERB tags, allowing us to use Ruby on our view page.

Go ahead and make some changes to your owner using this edit form, then place a binding.pry in your patch '/owners/:id' action and submit the form. Once you hit your binding, type params in the terminal.

I filled out my edit form like this:

Notice that I've unchecked the first two pets, Maddy and Nona, and checked the next two pets.

My params hash consequently looks like this:

{"owner"=>{"name"=>"Adele", "pet_ids"=>["3", "4"]},
 "pet"=>{"name"=>"Another New Pet"},
 "splat"=>[],
 "captures"=>["8"],
 "id"=>"8"}

Updating Owners in the Controller

Let's update our owner with this new information. Just as Active Record was smart enough to allow us to use mass assignment to not only create a new owner but to associate that owner to the pets whose IDs were contained in the "pet_ids" array, it is also smart enough to allow us to update an owner in the same way. In our Pry console in the terminal, let's execute the following:

@owner = Owner.find(params[:id])
@owner.update(params[:owner])

Now, if we type @owner.pets, we'll see that the owner is no longer associated to the pets with an ID of 1 or 2, but they are associated to pets 3 and 4:

@owner.pets
# => [#<Pet:0x007fd511d5e560 id: 3, name: "SBC", owner_id: 8>,
 #<Pet:0x007fd511d5e3d0 id: 4, name: "Fake Pet", owner_id: 8>]

Great! Now, we need to implement logic similar to that in our post '/owners' action to handle a user trying to associate a brand new pet to our owner:

patch '/owners/:id' do
    ####### bug fix
    if !params[:owner].keys.include?("pet_ids")
    params[:owner]["pet_ids"] = []
    end
    #######

    @owner = Owner.find(params[:id])
    @owner.update(params["owner"])
    if !params["pet"]["name"].empty?
      @owner.pets << Pet.create(name: params["pet"]["name"])
    end
    redirect "owners/#{@owner.id}"
end

NOTE: The bug fix is required so that it's possible to remove ALL previous pets from owner.

And that's it!

Creating and Updating Pets with Associated Owners

Now that we've walked through these features together for the Owner model, take some time and try to build out the same functionality for Pet. The form to create a new pet should allow a user to select from the list of available owners and/or create a new owner, and the form to edit a given pet should allow the user to select a new owner or create a new owner. Note that if a new owner is created it would override any existing owner that is selected.

Make sure you run the tests to check your work.

sinatra-complex-forms-associations's People

Contributors

annjohn avatar authorbeard avatar bacitracin avatar cernanb avatar dakotalmartinez avatar danielrancode avatar danielseehausen avatar dependabot[bot] avatar devinburnette avatar drakeltheryuujin avatar gj avatar gooryalhamed avatar ihollander avatar jnoconor avatar kaylee42 avatar kimgonzales avatar lcorr8 avatar lizbur10 avatar maxwellbenton avatar nicolefederici avatar pajamaw avatar preetness avatar rishter avatar rrcobb avatar schuylermaclay avatar sgharms avatar smulligan85 avatar sophiedebenedetto avatar victhevenot avatar yberdysh avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sinatra-complex-forms-associations's Issues

checkbox test

`require 'spec_helper'

describe "Pets Controller" do
describe "new action" do

it "can visit '/pets/new'" do
  get '/pets/new'
  expect(last_response.status).to eq(200)
end

it " loads form to create a new pet" do
  visit '/pets/new'
  expect(page).to have_field('pet_name')
end

it "has a form with a radio buttons for existing owners" do
  @owner1 = Owner.create(:name => "Cricky")
  @owner2 = Owner.create(:name => "Chris")

  visit '/pets/new'
  expect(page.has_unchooseed_field?(@owner1.id)).to eq(true)
  expect(page.has_unchooseed_field?(@owner2.id)).to eq(true)
end

it "has a field for creating a new owner" do
  visit '/pets/new'
  expect(page).to have_field(:owner_name)
end


it "creates a new pet and associates an existing owner" do
  @owner1 = Owner.create(:name => "Cricky")
  @owner2 = Owner.create(:name => "Chris")
  visit '/pets/new'
  fill_in "pet_name", :with => "Michael"
  choose(@owner1.id)
  click_button "Create Pet"
  @pet = Pet.last
  expect(@pet.name).to eq("Michael")
  expect(@pet.owner.name).to eq("Cricky")
end

  it " creates a new pet and a new owner" do
  visit '/pets/new'
  fill_in "pet_name", :with => "Pippa"
  fill_in "owner_name", :with => "Mary Nelson"
  click_button "Create Pet"
  @owner = Owner.last
  @pet = Pet.last
  expect(@pet.name).to eq("Pippa")
  expect(@pet.owner.name).to eq("Mary Nelson")
end

it "redirects to '/pets/:id' after form submissions" do
  @owner1 = Owner.create(:name => "Kristi")
  @owner2 = Owner.create(:name => "Kaitlin")
  visit '/pets/new'
  fill_in "pet_name", :with => "Joeseph"
  choose(@owner2.id)
  click_button "Create Pet"
  @pet= Pet.last
  expect(page.current_path).to eq("/pets/#{@pet.id}")
end

end

describe "edit action" do
before(:each) do
@owner = Owner.create(:name => "Carla")
@pet = Pet.create(:name => "Chewie", :owner_id => @owner.id)
end

it "can visit '/pets/:id/edit' " do
  get "/pets/#{@pet.id}/edit"
  expect(last_response.status).to eq(200)
end

it " loads form to edit a pet and his owner" do
  visit "/pets/#{@pet.id}/edit"
  expect(page).to have_field('pet_name')
  expect(page.has_chooseed_field?(@owner.id)).to eq(true)
  expect(page).to have_field('owner[name]')
end

 it "edit's the pet's name" do
  visit "/pets/#{@pet.id}/edit"
  fill_in "pet_name", :with => "Chewie Darling"
  click_button "Update Pet"
  expect(Pet.last.name).to eq("Chewie Darling")
end

it "edit's the pet's owner with an existing owner" do
  @adam = Owner.create(:name => "Adam")
  visit "/pets/#{@pet.id}/edit"
  choose(@adam.id)
  click_button "Update Pet"
  expect(Pet.last.owner.name).to eq("Adam")
end

it "edit's the pet's owner with a new owner" do
  visit "/pets/#{@pet.id}/edit"
  fill_in "owner_name", :with => "Samantha"
  click_button "Update Pet"
  expect(Pet.last.owner.name).to eq("Samantha")
end

end

end
`
This was the initial file for the pet_controller_spec. The 'choose' keyword is being used to interact with the checkboxes in the HTML, and I was having trouble passing the tests pertaining to that. When I looked at the other file for the owner_controller_spec I noticed that the 'check' keyword was being used. When I changed the instances in the pet_controller_spec I was able to pass the three tests pertaining to the checkboxes. I am not sure if this was an intentional thing or just a deprecated feature, but I wanted to bring it up just in case. The code below is the updated pet_controller_spec file:

`require 'spec_helper'

describe "Pets Controller" do
describe "new action" do

it "can visit '/pets/new'" do
  get '/pets/new'
  expect(last_response.status).to eq(200)
end

it " loads form to create a new pet" do
  visit '/pets/new'
  expect(page).to have_field('pet_name')
end

it "has a form with a radio buttons for existing owners" do
  @owner1 = Owner.create(:name => "Cricky")
  @owner2 = Owner.create(:name => "Chris")

  visit '/pets/new'
  expect(page.has_unchecked_field?(@owner1.id)).to eq(true)
  expect(page.has_unchecked_field?(@owner2.id)).to eq(true)
end

it "has a field for creating a new owner" do
  visit '/pets/new'
  expect(page).to have_field(:owner_name)
end


it "creates a new pet and associates an existing owner" do
  @owner1 = Owner.create(:name => "Cricky")
  @owner2 = Owner.create(:name => "Chris")
  visit '/pets/new'
  fill_in "pet_name", :with => "Michael"
  check(@owner1.id)
  click_button "Create Pet"
  @pet = Pet.last
  expect(@pet.name).to eq("Michael")
  expect(@pet.owner.name).to eq("Cricky")
end

  it " creates a new pet and a new owner" do
  visit '/pets/new'
  fill_in "pet_name", :with => "Pippa"
  fill_in "owner_name", :with => "Mary Nelson"
  click_button "Create Pet"
  @owner = Owner.last
  @pet = Pet.last
  expect(@pet.name).to eq("Pippa")
  expect(@pet.owner.name).to eq("Mary Nelson")
end

it "redirects to '/pets/:id' after form submissions" do
  @owner1 = Owner.create(:name => "Kristi")
  @owner2 = Owner.create(:name => "Kaitlin")
  visit '/pets/new'
  fill_in "pet_name", :with => "Joeseph"
  check(@owner2.id)
  click_button "Create Pet"
  @pet= Pet.last
  expect(page.current_path).to eq("/pets/#{@pet.id}")
end

end

describe "edit action" do
before(:each) do
@owner = Owner.create(:name => "Carla")
@pet = Pet.create(:name => "Chewie", :owner_id => @owner.id)
end

it "can visit '/pets/:id/edit' " do
  get "/pets/#{@pet.id}/edit"
  expect(last_response.status).to eq(200)
end

it " loads form to edit a pet and his owner" do
  visit "/pets/#{@pet.id}/edit"
  expect(page).to have_field('pet_name')
  expect(page.has_checked_field?(@owner.id)).to eq(true)
  expect(page).to have_field('owner[name]')
end

 it "edit's the pet's name" do
  visit "/pets/#{@pet.id}/edit"
  fill_in "pet_name", :with => "Chewie Darling"
  click_button "Update Pet"
  expect(Pet.last.name).to eq("Chewie Darling")
end

it "edit's the pet's owner with an existing owner" do
  @adam = Owner.create(:name => "Adam")
  visit "/pets/#{@pet.id}/edit"
  check(@adam.id)
  click_button "Update Pet"
  expect(Pet.last.owner.name).to eq("Adam")
end

it "edit's the pet's owner with a new owner" do
  visit "/pets/#{@pet.id}/edit"
  fill_in "owner_name", :with => "Samantha"
  click_button "Update Pet"
  expect(Pet.last.owner.name).to eq("Samantha")
end

end

end
`

Typo

In this line: "Great! Now, we need to implement logic similar to that in our post '/owners' action to handle a user trying to associate a brand new pet to our owner:"

The "post '/owners'" should actually be "patch '/owners'".

Badly done lab

Hey guys, I don't know a nice way to say this, but this lab is a sloppy mess. I'd pull it from the curriculum until you either change the directions or change the repo to match the directions.

Best,
A

needs review

@jmburges @AnnJohn

hey, so i know i was supposed to just make notes for this for vic to do but my class needs something along these lines to get through the more advacned sinatra stuff over the break so i threw something together. this is the walkthrough of complex forms with associations. also has a note on what is seed file, how to use it. i'm going to put this in the web-1115 track before playlister and nyc sinatra. feel free to use it for LV/add tests/disregard.

A closed </input> tag in example

Example:

views/owners/new.erb

<% @pets.each do |pet| %>
<%= pet.name %>

<% end %>

There is no need for a closing input tag. :)

iteration issue for update method

In the below code for the UPDATE method, the iteration should go through @owner.pets instead of @Pets

edit.erb

<h3>Existing Pets</h3>
<% @pets.each do |pet| %>
  <input type="checkbox" name="owner[pet_ids][]" id="<%= pet.id %>" value="<%= pet.id %>" <%='checked' if @owner.pets.include?(pet) %>><%= pet.name %></input><br>
<% end %>
<br>

Tests don't pass even with solution code!

I was failing tests even though I copied exactly from the read me, so I decided to try using the code from the solution .I copied the solution code from the model, view, and owner_controller into my app and still failed tests for owner. Clearly there's something wrong here.

Capybara checking for different fields on new and edit forms

In the pets_controller_spec, Capybara is looking for owner checkboxes for the new action, but radio buttons for the edit action. Is this intentional? Shouldn't they be the same for consistency?

new action

    it "creates a new pet and associates an existing owner" do
      @owner1 = Owner.create(:name => "Cricky")
      @owner2 = Owner.create(:name => "Chris")
      visit '/pets/new'
      fill_in "pet_name", :with => "Michael"
      **check(@owner1.id)**
      click_button "Create Pet"
      @pet = Pet.last
      expect(@pet.name).to eq("Michael")
      expect(@pet.owner.name).to eq("Cricky")
    end

edit action

    it "edit's the pet's owner with an existing owner" do
      @adam = Owner.create(:name => "Adam")
      visit "/pets/#{@pet.id}/edit"
      **choose(@adam.id)**
      click_button "Update Pet"
      expect(Pet.last.owner.name).to eq("Adam")
    end

@aturkewi

Wrong grammar

Please check the paragraph: "This is code you should be pretty familiar with by now. We are simply creating and saving an instance of our Owner class and creating and saving two new instances of the Pet class."

No App folder

Lab says:

Open up app/views/owners/new.erb and you should see the following code:

<h1>Create a new Owner</h1>
 
<form action="/owners" method="POST">
  <label>Name:</label>
 
  <br>
 
  <input type="text" name="owner[name]" id="owner_name">
 
  <input type="submit" value="Create Owner">
</form>

There's no app folder or views folder or owners folder. That's fine, but the instructions are not in sync with what is in the lab.

No db/seed.rb file

The readme says: "Go ahead and open up the seed file in this app, db/seeds.rb. You should see the following:" but there is no seed file. Just FYI.

View is pulling data directly from database in the README

In a previous lesson we are taught that you should never pull data from the database in a view but rather, create a helper method in the controller and use that to access the data in the view. The code in this README seems to be doing exactly what were taught not to do.

In the CREATING A NEW OWNER AND ASSOCIATING THEM WITH A NEW PET section the code to create dynamic checkboxes is as follows
Choose an existing pet:



<%Pet.all.each do |pet|%>
<%=pet.name%>
<%end%>

I believe Pet.all is pulling from the database. The same thing occurs later in the README in the:
EDITING OWNERS AND ASSOCIATED PETS section

Just wanted to let you know as it seems to be in conflict with earlier lessons. Thanks. -Scott

Refactor post 'owners'

This refactoring simplifies the creation of the optional extra pet and optimizes the method returns/SQL statements.

  post '/owners' do
    owner = Owner.new(params[:owner])
    owner.pets.new(name: params[:pet][:name]) unless params[:pet][:name].empty?
    owner.save
    redirect "/owners/#{owner.id}"
  end

LoadError on running tux

After running bundle install and rake db:migrate, running the tux command results in the following error:

/home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-rack-0.2.1/lib/ripl/rack.rb:38:in &#96;eval': cannot infer basepath (LoadError)
	from (eval):1:in &#96;block in initialize'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in &#96;instance_eval'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in &#96;initialize'
	from (eval):1:in &#96;new'
	from (eval):1:in &#96;initialize'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-rack-0.2.1/lib/ripl/rack.rb:38:in &#96;eval'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-rack-0.2.1/lib/ripl/rack.rb:38:in &#96;initialize'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-rack-0.2.1/lib/ripl/rack.rb:47:in &#96;new'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-rack-0.2.1/lib/ripl/rack.rb:47:in &#96;instance'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-rack-0.2.1/lib/ripl/rack.rb:18:in &#96;rack'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-rack-0.2.1/lib/ripl/rack.rb:9:in &#96;before_loop'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-multi_line-0.3.1/lib/ripl/multi_line.rb:18:in &#96;before_loop'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-0.7.1/lib/ripl/readline.rb:6:in &#96;before_loop'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-0.7.1/lib/ripl/completion.rb:5:in &#96;before_loop'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-0.7.1/lib/ripl/shell.rb:34:in &#96;loop'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-0.7.1/lib/ripl/runner.rb:49:in &#96;start'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/ripl-0.7.1/lib/ripl/runner.rb:31:in &#96;run'
	from /home/crce/.rvm/gems/ruby-2.3.0/gems/tux-0.3.0/bin/tux:7:in &#96;<top (required)>'
	from /home/crce/.rvm/gems/ruby-2.3.0/bin/tux:23:in &#96;load'
	from /home/crce/.rvm/gems/ruby-2.3.0/bin/tux:23:in &#96;<main>'
	from /home/crce/.rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in &#96;eval'
	from /home/crce/.rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in &#96;<main>'

After checking out this bug in ruby, William and I narrowed it down to a problem with require_relative as mentioned in the final note:

#16 Updated by julik (Julik Tarkhanov) almost 2 years ago

This is actually very pertinent for Rack as well, because currently config.ru does not support require_relative which is very counterintuitive.

config.ru should be using require instead of require_relative. Props to @WilliamBarela for pointing this out.

Owner ID mismatch in Readme

@owner = Owner.create(params["owner"])

=> #<Owner:0x007fdfcc96e430 id: 2, name: "Adele"> ***<- here the Owner's ID is listed as 2

@owner.pets

=> [#<Pet:0x007fb371bc22b8 id: 1, name: "Maddy", owner_id: 5>, #<Pet:0x007fb371bc1f98 id: 2, name: "Nona", owner_id: 5>] ***<- here the same owner (logical assumption from readme flow) is listed as having an ID of 5 instead of 2.

This may be minor, but eliminating small discrepancies can go a long way towards eliminating unnecessary confusion :)

4 tests in '/owners/:id/edit' are BROKEN

edit action
    can visit '/owners/:id/edit' (FAILED - 1)
    '/owners/:id/edit' loads form to edit an owner and his pets (FAILED - 2)
    edit's the owner's name (FAILED - 3)
Locator 2 must be an instance of String or Symbol. This will raise an error in a future version of Capybara.
    edit's the owner's pets with an existing pet (FAILED - 4)
    edit's the owner's pets with a new pet (FAILED - 5)

Code provided in codealong does not pass tests

Specifically it never hits the patch route when editing. I could not figure out what was missing and referred to the solution branch, but to no avail. The use Rack::MethodOverride was included correctly in config. The hidden form input with patch method was used. It just would not work.

Pet belongs to an 1 owner, etc.

A few things I found complicated when I tried to get the tests to pass. Note: based on the description and owner code, I thought I had good understanding of the Pet requirements, so I coded and tested with shotgun and then ran the tests.

  • pet belongs to a single owner and so for pet new/edit, user should be able to only select 1 owner (radio button vs checkbox) or create a new one. Spec for pet new requires checkbox.
  • similarly, I think the pet erbs and controller are sometimes using an [] for pet's owner but there is only 1 owner. (I'm not sure if I am mis-interpreting here)
  • not sure if this will be addressed in another lesson but new owners can steal pets. Shouldn't the pet list on the new owner form just be "un-owned" pets?
  • not sure if critical for this small app but the views seems to sometimes access model (ex. erb will have Pet.all.each). I thought best practice would be for controller to store the "all" for the erb to render. Related to stealing pets, the controller could retrieve list of pets in need of owners, and then view would just render that list.
    Going to walk my dog now. Thanks!

Extra '@owner.save' not necessary

In the 'post /owners' method of the ReadMe, I noticed an extra save added after the instance of owner has been persisted, and after running through Pry with a coach we found that it is not needed.

post '/owners' do
@owner = Owner.create(params[:owner])
if !params["pet"]["name"].empty?
@owner.pets << Pet.create(name: params["pet"]["name"])
end
#binding.pry
#@owner.save
redirect "owners/#{@owner.id}"
end

Spelling error in last paragraph

The form to create a new pet should allow a user to select from the list of available owners and/or create a new owner, and the forym to edit a given pet should allow the user to select a new owner or create a new owner.

"forym"

Capybara Choose vs Check

spec/controllers/pets_controller_spec.rb

Lines:
36
59
94

Operator/method "choose" not finding checkboxes formatted similarly to the owners forms outlined in the walkthrough.

Owners controller spec uses "check" operator, when I switched Choose to Check in the pets controller spec all tests passed fine.

a Pet belongs_to one Owner but spec expects checkboxes to select multiple owners in the form for a new pet

in pets_controller_spec.rb the capybara methods used are check(@owner1.id) and expect(page.has_unchecked_field?(@owner2.id)).to eq(true). This forces the student to use checkboxes in their pets/new.erb view.

from the solution branch:

<%Owner.all.each do |owner|%>
    <input type="checkbox" name="pet[owner_id]" id="<%= owner.name %>" value="<%=owner.id%>"><%=owner.name%></input>
  <%end%>

Since a pet can only have one owner, students use radio buttons and then get confused as to why the tests expect checkboxes.

choose I think is the capybara method that should be used, possibly some other changes.

Refers to ERB tags when discussing Ruby code in application_controller.rb

Under Dynamically Generating Checkboxes, the README states, "We use ERB to get all of the pets with Pet.all, then we iterate over that collection of Pet objects and generate a checkbox for each pet."

However, Pet.all is set to an instance variable @Pets in application_controller.rb. We do not use ERB to generate the list of all pets — that action is performed by the controller and is made available in the associated view.

Issue with Fork

I had an issue with many of the files showing <<<<<<< Head ======== >>>>>> with long string with numbers and letters at the end.
views/owners/owners_controller.rb
views/owners/new.erb
views/pets/edit.erb
views/pets/new.erb
Gemfile

Also missing are some of the spec files and one of the controllers.

Test spec discrepancies

In pets_controller_spec.rb

  1. Line 13 requires a field "pet[name]", while other tests require "pet_name" (see lines 35, 45, 58, 86)

  2. Line 73, test for get 'pets/:id/edit' calls get 'owners/:id/edit'

RSPEC Test testing for the wrong view page

The RSPEC test under "Pets Controller", "edit action" states:

it "can visit '/owners/:id/edit' " do
get "/owners/#{@owner.id}/edit"
expect(last_response.status).to eq(200)
end

This is the same test under "Owners Controller", "edit action"... worded exactly the same.

I believe this code is incorrect (for the pets controller test section). It seems like the test should ensure that the pets/:id/edit page works. So:

it "can visit '/pets/:id/edit' " do
get "/pets/#{@owner.id}/edit"
expect(last_response.status).to eq(200)
end

rake db:seed issue in Learn?

Hello,

Each time I've been instructed to run rake db:seed in recent labs, I receive the following message directly below that in the terminal "/usr/local/rvm/gems/ruby-2.6.1/gems/activesupport-4.2.5/lib/active_support/core_ext/object/duplicable.rb:85: warning: BigDecimal.new is deprecated; use BigDecimal() method instead."

I am not sure if this is preventing the seed or not, but felt that I should share. I will ask my cohort leader about a way to tell if the seed has connected to the db.

Thanks,
Ryan

MVC violations + non-RESTful routing

Alberto Carreras [Yesterday at 9:52 PM]
in #nyc-mhtn-web-051418
Just a heads up that this lab https://github.com/learn-co-students/sinatra-complex-forms-associations-nyc-web-051418 is a collection of bad practices: POST for editing (does not recognize put or patch for some reason), Views with explicit class access (Pet.all instead of @Pets), checkbox instead of radio for pets (selection two options could bring error)… Should be revised. (If I’m wrong in any point, please, bring it to my attention) (edited)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.