Code for Thought

Alias in Rails

It is our last full week coding at Flatiron, and we are working hard on our final projects. The application we are building allows users to both post food items they will not use and allow others to claim those items posted by others. We wanted to make sure individuals using the application could be both Posters and Claimers. In order to accomplish this we had to alter our associations and create new aliases. It was a great review of these concepts and working it out through our new application really helped me understand them and how to use them.

When you create an association, Rails makes two major assumptions

  • The class of the model your association points to is based directly off of the name of the association
  • The foreign key in a belongs_to relationship will be called yourassociationname_id.

Any time you go away from these defaults, you need to let Rails know what kind of class to look for and which foreign key to use.

Suppose you want to refer to a model as two different things and setup the associations to reflect this. We used this in a Flatiron lab that referred to AirBnB. In this lab a single User could be a Host or a Guest. We wanted to be able to refer to the same individual as both a host and a guest throughout our app and know that this was actually the same user. This is called aliasing - where we are giving one user two names throughout the app.

In our final project we also have a user, however, we wanted to refer to the user as someone who posts food to our site (a poster) as well as someone who could claim food (a claimer). Here we want access to :poster_id and :claimer_id and not just :user_id.

To do this we had to modify our associations in our models. Once we modify these associations we can actually refer to these aliases throughout the app. Rails knows that there will be times when you want to customize the behavior of your belongs_to association reference. These customizations are accomplished by passing options and scope blocks when you create the association. You can use the :class_name option to give a new model name. For example, in our app, if a food item belongs to a Poster, but the actual name of the model containing users of our site is User, you’d set things up this way:

1
2
3
4
class FoodItem < ActiveRecord::Base
  belongs_to :poster, :class_name => "User", :foreign_key => "poster_id"
  belongs_to :claimer, :class_name => "User", :foreign_key => "claimer_id"
end

The next step is to set the set the alias foreign key’s directly. The :foreign_key option lets you set the name of the foreign key like this:

1
2
3
4
class User < ActiveRecord::Base
  has_many :food_items, :foreign_key => "poster_id"
  has_many :food_items, :foreign_key => "claimer_id"
end

The basic concept here is that rails allows you to have aliases by following the convention that applies to all association - the models name have to be referred (we are just using :class_name to refer to the names we made up) and then we have to get the app using the correct forgin key with :foreign_key.

SustainableAgriculture.merge(TECH)

As we enter into project mode at the Flatiron School I am increasingly excited about applying everything we have learned to build interesting web applications. My passion and background is in sustainable agriculture and food access. Food is one of the biggest issues of our time, affecting our health, our environment, and our economy. I am passionate about improving our food system and helping people have better access to healthy food. I believe that supporting local farmers is an essential component of ensuring the health of our food system and our bodies.

Entering the world of tech has been a scary journey. While I am excited about my new skills I am was also worried that they may take me away from my passion for food. I was initially worried that if I wasn’t building gardens or doing fresh-food tastings in low-income communities that I wouldn’t be making a difference. However, after being immersed in the tech industry I have realized that the power of tech can, in many ways, affect the food movement and possibly much more so than planting urban gardens. After all, Uber has changed the taxi industry while owning no vehicles and Airbnb has changed the hotel industry while owning no real estate.

I think there is so much potential to change the way we grow, distribute, consume and dispose of food if we combine our food systems with improved technology. Imagine if we Uberfied food distribution, creating infrastructure for local farmers to distribute their food or if we created an app to help restaurants lower their food waste.

Amazing apps already exist to help consumers learn what they should eat and where they can find clean sustainable produce. Checkout some apps here.

I am not the only one who is interested in how food and tech can come together. According to Fortune Magazine, “Between 2013 and 2014 Silicon Valley’s interest in backing agriculture and food-related startups soared, doubling in terms of deal size, according to data from the Cleantech Group.”

It will be exciting to see where this takes us meanwhile I am excited to enter the tech industry while there is this excitement around food!!

Articles

Farming data continues to be hot in Silicon Valley

Silicon Valley’s clean tech investors eyeing sustainable food, experts say

Some Good Resources

Food + Tech - This is my favorite Website right now. Food and Tech is a platform for good food innovation. They help people launch, grow and transform good food businesses through news and analysis, online business courses and hackathons.

Food and Ag APIs -

USDA National Farmers Market Directory API - This web API provides information about U.S. farmers market locations, directions, operating times, product offerings, and accepted forms of payment.

Food and Ag Gems -

FoodInfo - FoodInfo is a ruby gem that retrieves food nutritional information from various online data sources.

Garden - Allows you to organize your seeds in different formats. Typical seeds.rb, yaml fixtures, and a variety of spreadsheet formats.

Rails Routes!

Routes are a very confusing topic that have taken me a while to understand and trying to understand rails without understanding routes looks kind of like this…

The basic concept is that rails routes are how rails apps read a URL. When a user goes to a certain URL, the URL is sent to the rails routes folder (located in config/routes.rb). If the routes folder recognizes the URL, it then looks inside it’s corresponding controller for actions (or methods) that match that URL. Basically, it’s a way to redirect incoming requests to controllers and actions within the app.

Resourceful Routes

Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code.

resources :photo

creates the following information…

a brick

Tip - you can also add multiple resources in a single line:

resources :photo, :magazine, :animal

You can think of the controller/action part of the routes as a direction. “photo#index” tells your app to go to the photo controller and the index action and look for further instructions there.

If you don’t want the user to have access to all 7 routes that are created when using resources, rails provides the “only” keyword so you can specify exactly what you want to be created.

resources :photo, :only => [:index, :show]

This will only create the photo#index and photo#show.

Non-Resourceful Routes

If you wish to create routes that do not fit the 7 routes that are created with resources, you can make custom routes with the HTTP helper methods. These include GET, POST, PATCH, PUT and DELETE. An example of this is below

GET "/photo", to: photo#new' GET photo/:id' => photos#show'

You can even make your routes respond to more than one HTTP helper method using :via and :match.

match photo/:id' => photos#show', via: [:get, :post]

If you would like to change the URL of your custom route you can do so with the as keyword…

Now that I have a better understanding of routes, I can hopefully master rails as well as this dog has mastered catch!

Don’t forget you can always see all your routes by typing in “rails routes” into your terminal or going to localhost:3000/rails/info/routes

For a more comprehensive overview of Rails Routes checkout the Rails Guides!!!!

The Magic of Rails

This week we were introduced to rails. At a glance rails just looks like a ton of files that mysteriously appear when a few lines of code are typed into the terminal. I have spent the last week and a half trying to master sinatra, a small and flexible web framework much like rails but with no fancy scaffolding (a term I go into a bit below) and no guiding principles. After having to create many of the files manually in sinatra, seeing a rails app created for the first time left me with a reaction of confusion and awe.

Here I am going to go over some basic rails terminology and principles.

First, What Exactly is Rails?

Rails is an application development framework built using the Ruby language which aims to make the developer’s experience seamless by already including the structure that is needed to create an app with a simple rails new command.

The Rails Guides brag that rails “allows you to write less code while accomplishing more than many other languages and frameworks.” Without a framework like rails, a programmer would have a huge job to implement all the required infrastructure to get an app up and running before they could begin to start creating their app. Rails creates this infrastructure for the developer.

One thing that makes rails popular is its guiding principles:

Don’t Repeat Yourself: Known by the acronym DRY, the Rail’s Guide’s state, “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” This principle is to help the developer write code that has less bugs because when code is duplicated, an application becomes more complex, making it more difficult to maintain.

Convention Over Configuration: “Rails has opinions about the best way to do many things in a web application, and defaults to this set of conventions, rather than require that you specify every minutiae through endless configuration files.” This principle means you’ll be productive. You won’t spend time setting up configuration files. You’ll spend less time thinking about where things go and what names to assign. And, because other developers have learned the same conventions, it is easier to collaborate.

Some Basic Terminology

Model/View/Controller pattern - Rails is built around a model-view-controller pattern. This pattern helps in separating the data (model), the logic (controller), and the display (view).

Models - The model represents information that you are using in your application.

Controllers - The controller, as the name suggests, controls the models and the view. It receives user commands and communicates with the models to process the commands. It then tells the view how to display to the user.

Views - The view is how things are visually displayed to the user. It determines how the user interacts with the application and data is presented to the user. The views are written in html or ERB, a ruby embedded language.

CRUD - CRUD is an acronym for the basic operations performed when an app uses a database for storing data. The acronym stands for —

-Create new records in the database

-Read or show the records in the database

-Update existing records

-Destroy or delete records

Scaffolding - Scaffolding is like a build in CRUD wizard. Because these CRUD actions are done so often rails provides commands to make creating them easier.

A Basic Guide to Octopress

Here are some commands to remember to help your octopress experience go smoothly!

1
2
# Creating a new post - pages can be found in source/_posts.
rake new_post['Title of the Post']
1
2
# Creating a new page 
rake new_page['Title of the page']
1
2
# Previewing your work at http://localhost:4000
rake preview
1
2
3
# Publishing Posts
rake generate
rake deploy

I hope to add to this as I continue to find new octopress commands useful.

Changing the Way I Think About Complex Problems

I knew that doing the Flatiron Web-Immersion program would push me in many ways. The expectations are to go from zero programming skills to 100 in 12 short weeks. This means that every single day we are introduced to new concepts that seem so big, so important and so impossible to learn. It is overwhelming and can make you feel like you can’t accomplish any of it. Over the past three weeks I have mostly felt like a failure. Why can’t I understand these concepts? In the first week I understood a lot of what was going on. Simple ruby concepts like how to access values in a hash or in an array or how a conditional statement worked, I could understand, but the moment you asked me to do something more complex, I froze.

About half way through this past week I realized what one of the things that was holding me back was my mentality. I was spending so much energy on “I can’t” instead of telling myself “you can, just go one simple step at a time”. When working on more complex problems, I started telling myself, “Start with what you know. I can access these values in a hash, and then use binding.pry to figure out the rest one step at a time.” This mentality shift has helped in so many ways. Number one, I am spending less energy on “I can’t do this” and more on learning how to actually do it. And number two, I feel less paralyzed when hard concepts are introduced to me.

Break Down Each Task to Things I Understand

One example of my new outlook to understand more complex concepts (breaking things down to the concepts I do get and moving forward from there) can be seen when looking at our NYC Pigeon’s Lab that asked us to take a hash that looked like this…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
pigeon_data = {
  :color => {
    :purple => ["Theo", "Peter Jr.", "Lucky"],
    :grey => ["Theo", "Peter Jr.", "Ms. K"],
    :white => ["Queenie", "Andrew", "Ms. K", "Alex"],
    :brown => ["Queenie", "Alex"]
  },
  :gender => {
    :male => ["Alex", "Theo", "Peter Jr.", "Andrew", "Lucky"],
    :female => ["Queenie", "Ms. K"]
  },
  :lives => {
    "Subway" => ["Theo", "Queenie"],
    "Central Park" => ["Alex", "Ms. K", "Lucky"],
    "Library" => ["Peter Jr."],
    "City Hall" => ["Andrew"]
  }
} 

And create one that looked like this…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
pigeon_list = {
  "Theo" => {
    :color => ["purple", "grey"],
    :gender => ["male"],
    :lives => ["Subway]"
  },
  "Peter Jr." => {
    :color => ["purple", "grey"],
    :gender => ["male"],
    :lives => ["Library]"
  },
  "Lucky" => {
    :color => ["purple"],
    :gender => ["male"],
    :lives => ["Central Park"]
  },
  "Ms. K" => {
    :color => ["grey", "white"],
    :gender => ["female"],
    :lives => ["Central Park"]
  },
  "Queenie" => {
    :color => ["white", "brown"],
    :gender => ["female"],
    :lives => ["Subway"]
  },
  "Andrew" => {
    :color => ["white"],
    :gender => ["male"],
    :lives => ["City Hall"]
  },
  "Alex" => {
    :color => ["white", "brown"],
    :gender => ["male"],
    :lives => ["Central Park"]
  }
} 

At first I froze. This seems impossible, how the heck can I switch values for keys and vise versa!? However, after I took a step back and remembered that accessing values is the same in this case as it is in one of our easier labs, I was able to breathe and start iterating through the hash, getting out the values I needed and setting up my new hash.

1
2
3
4
5
6
7
8
9
10
11
12
13
def nyc_pigeon_organizer(pigeon_data)
  new_hash = {}
  pigeon_data.each do |trait_group, trait_hash|
    trait_hash.each do |trait_details, names_array|
      names_array.each do |name|
      new_hash[name] ||= {}
      new_hash[name][trait_group] ||= []
      new_hash[name][trait_group] << trait_details.to_s
    end
  end
end
new_hash
end 

Helper Methods

Another helpful way to break down tasks is with helper methods. A helper method is a method that helps another method to perform its task. These are typically used when a method has to perform a complicated task that is composed of several smaller tasks. These methods can reduce confusion and help make our tasks more clear.

We saw helper methods come to the rescue one of the more complex hash labs - Hashketball. In this lab we broke down methods like how to find the number of points scored into two different methods. This let us organize the data into a simpler form and make solving the problem easier.

1
2
3
def num_points_scored(player_name)
  find_player_name(player_name)[:stats][:points] 
end
1
2
3
4
5
6
7
8
#helper method 
def find_player_name(player_name) 
  game_hash.each do |location, team_hash| 
    if team_hash[:players][player_name] 
      return team_hash[:players][player_name] 
    end
  end
end

I realized that code is code - a method used to do a certain task will always do that task. This part of code will alway be the same, but what a developer has control over is how they solve the problem. The logic they use, the specific methods they know that will help them solve the problem, and as in my case, their overall mindset in tackling a particularly complex problem. What I really learned this week was that aspect of coding. That the way I approach a problem may make it harder or easier to solve. I obviously need to understand the code behind solving the problem but I can get to those solutions easier when I take it slow, think about what I know, find out what I do not know and move in an orderly manner through any particular problem.

Your Basic Guide to Git

When I first learned about Git and GitHub I assumed it was something like Google Docs - a place to store your code online so that you could access it anywhere, share it and collaborate with anyone also using github. While github is all these things, I was missing the biggest advantage to git and github. Git is a version control platform - meaning that it can save your changes along the way and you can go back to each change that you have saved and revisit it.

I remember when writing my college papers, I would continually save my work in case something crashed and I lost everything. With word processing programs the changes you save are permanent. If I deleted a paragraph or changed any aspect of the paper and I wanted to go back to what I had before, I would have had to make a separate document which would have gotten very messy. However, If you were using a version control program like git, you could get your changes back much more easily. While working on that paper you could have “committed” or (saved) the changes along the way and like magic you could get back any of these changes!

Version control is an amazingly useful however, because it is executed through the command line (or terminal) it can be kind of confusing at first. So what are some basic git commands to know if you want to use git as your version control?

$ git init - This creates a new repository, (or “repo” for short), which basically tells your computer you are going to use git.

$ git status - Running this command will tell you exactly what is happening in git. Are there files that you have modified and haven’t been saved within git yet? git will let you know if you run this command.

$ git add file_name or $ git add . -This command tells your computer that you are about to save a file. It will put the file in a staging area that tells the computer, “Hey - I am about to tell you to save this file”. If you want to save all the files that have been modified you can use $ git add .

$ git commit -m “your message here” - Here you are saving the files with a little message. This message is for you to look back on and remember why you made changes and why you are saving them at this stage in your project.

$ git log -This command allows you to see all the commits or times you have saved your files throughout your project. You can look through them and if you decide you want to go back to one of these versions of your project it is easy to do so.

Using Git with GitHub

Github is the online or remote location you can store your files so that you can share them, save a copy remotely, and more easily see the changes you have made each time you commit a change.

You have to first create a remote repository in your github account that has the same name as directory where you have stored your files on your computer. Next you can start “pushing” or sending your files into your github repository. Here are the commands to know in order to do this.

$ git remote add origin https://github.com/hannahlw/my_project.git - (the url should be the url of your remote repo). This command first tells your computer that there is a remote place for it to store your files you are saving with git. Next it names that remote repo “origin”. Finally, it tells the computer where the newly named repo is located by giving the url.

$ git push -u origin master - This command will actually send or push the files to your github account.

Now you should now see your code in your GitHub repository!

Happy committing!

Hannah

So You Want to Be a Web-Developer?

Tomorrow is my first day of The Flatiron Program and I expect the next three months will be super intense and, I hope, super rewarding in the end.

My background is not in code. In fact I literally had to google “what is code?” when I first started. I found web-development when I moved to Philly with my husband who just started vet school and I was left without a close group of friends and without an interesting job (I nannied which was so fun but limited my conversations with adults even more). I had just binged watched all of Gossip Girl and I realized I needed to stimulate my brain somehow or I was going to get lost in this world of Netflix and my comfy couch.

I started googling fun stimulating things to do and I stumbled across Codecademy and through “learning a new skill and being able to build something in the process – this could be really cool”. I had fun messing around and when I told my brother who is engaged in the NY tech scene he said something like “you know you can actually make a career out of that? Check out The Flatiron School.” I did and the rest is history.

After about a year of taking classes on and off through Codecademy, Treehouse and Girl Develop It, code is thrilling and fun when I get it however, most of the time it is still really hard and confusing. I am super excited for the chance to learn with other people, have instructors, and a curriculum to steer me in the right direction.

Here’s to the next three months!