Skip to content

Instantly share code, notes, and snippets.

@gstark
Last active March 29, 2018 14:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gstark/4818d620286dbccb0d0f to your computer and use it in GitHub Desktop.
Save gstark/4818d620286dbccb0d0f to your computer and use it in GitHub Desktop.
Intro to Rails Crash Course

Weclome to the Iron Yard Intro to Rails Crash Course

First step is to install the correct version of the Ruby environment:

rvm install ruby-2.4.2

Install all the libraries we need

bundle install

Generate a data model for our truck. We will track the location description and its latitude and longitude

rails g scaffold Truck name:string location:string latitude:float longitude:float

Migrate the database

rails db:migrate

Lets add the ability to geocode from the location to the latitude and longitude

Edit the file app/models/truck.rb and add these lines inside the class and end keywords

  geocoded_by :location
  after_validation :geocode
rails generate controller Pages home

Edit the file config/routes.rb and add this within the Rails and end keywords

root 'pages#home'

Edit the file app/controllers/pages.rb and replace the

def home
end

with the following:

def home
  @trucks = Truck.all
end

Edit the file app/views/pages/home.html.erb

Replace the contents with

  <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css" />

  <div id="map"></div>

  <script>
  var map = L.map('map').setView([27.768, -82.633], 10);
  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: 'gavinstark.806a776b',
    accessToken: 'pk.eyJ1IjoiZ2F2aW5zdGFyayIsImEiOiIxZjVmODFhYWQ2NjIyZGY1MTQ5MzM3ZTE2MWNkMDkxMiJ9.HG1IbUfea4FfcJ0WrY7Pqg'
  }).addTo(map);
  <% @trucks.each do |truck| %>
    var marker = L.marker([<%= truck.latitude.to_f %>, <%= truck.longitude.to_f %>]).addTo(map);
    marker.bindPopup('<%= link_to truck.name, truck_path(truck) %><br/><%= truck.location %><br/>');
  <% end %>
  </script>
Create the file `app/assets/stylesheets/map.css`
Place the contents:
```
#map {
height: 600px;
}
.map-image {
width: 100px;
height: 100px;
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment