Building a small rails app that can search by postcode(zipcode) and radius, so it responds with contractors that are within that radius/postcode.
i can do Location.near("M20 2WZ", 15) in the rails console which gives me the relevant info.
=> #<ActiveRecord::Relation [#<Location id: 12, company_name: "Redbridge Interiors Ltd", address: "16 Kennedy St", city: "manchester", postcode: "M2 4BY", latitude: 53.4799243, longitude: -2.2436708, created_at: "2017-07-11 11:39:03", updated_at: "2017-07-11 11:39:03">, #<Location id: 11, company_name: "Manchester Electrical Contractors Ltd", address: "Unit 9, The Schoolhouse, Second Ave", city: "Manchester", postcode: "M17 1DZ", latitude: 53.4646868, longitude: -2.3097547, created_at: "2017-07-11 11:36:57", updated_at: "2017-07-11 11:36:57">, #<Location id: 10, company_name: "J Hopkins (Contractors) Ltd", address: "Monde Trading Estate, Westinghouse Rd", city: "manchester", postcode: "M17 1LP", latitude: 53.4658142, longitude: -2.3278817, created_at: "2017-07-11 11:35:40", updated_at: "2017-07-11 11:35:40">]>
When i implement this in the app i get a url http://localhost:3000/locations?utf8=%E2%9C%93&search=m20+2wz but get no info/data/locations
schema.rb
create_table "locations", force: :cascade do |t|
t.string "company_name"
t.string "address"
t.string "city"
t.string "postcode"
t.float "latitude"
t.float "longitude"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
location.rb
class Location < ApplicationRecord
geocoded_by :full_address
after_validation :geocode, :if => :address_changed?
def full_address
[address, city, postcode].compact.join(',')
end
end
locations.controller.rb
class LocationsController < ApplicationController
def index
@locations = Location.all
if params[:search].present?
@locations = Location.near(params[:search], 10, :order => :distance)
else
@locations = Location.all.order("created_at DESC")
end
end
def new
@location = Location.new
end
def show
@location = Location.find(params[:id])
end
def create
@location = Location.new(location_params)
if @location.save
flash[:success] = 'Place added!'
redirect_to root_path
else
render 'new'
end
end
private
def location_params
params.require(:location).permit(:company_name, :address, :city,
:postcode, :latitude, :longitude)
end
end
index.html.erb
<div class="container">
<div class="starter-template">
<h3>SubContractor Postcode search</h3>
<p class="lead">Use this postcode search to quickly find subcontractors in your area</p>
<p><%= form_tag locations_path, :method => :get do %>
<%= text_field_tag :search, params[:search], placeholder: "e.g M20 2WZ" %>
<%= submit_tag "Search Near", :name => nil %>
</p>
<% end %>
</div>
</div>
routes.rb
Rails.application.routes.draw do
resources :locations, except: [:update, :edit, :destroy]
root 'locations#index'
end
You are not displaying the locations in index.html.erb
Add this in your index.html.erb
<% @locations.each do |location| %>
<%= location.city %>
<% end %>