Когато текущият потребител създаде публикация, иска да знае местоположението на потребителя чрез метода за обръщане на IP в Geo-coder. За това създадох модел на публикация, потребител и местоположение. Преминах през railscasts и се научих да инсталирам Geocoder и мога да намеря географска ширина, дължина чрез адрес. Сега как да интегрирате потребителски идентификатор от устройство към геокодер, за да определите текущото потребителско местоположение.
class Location < ActiveRecord::Base
belongs_to :user
geocoded_by :address
after_validation :geocode, :if => :address_changed?
end
class LocationsController < ApplicationController
before_action :set_location, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
#location = request.location
@locations = Location.all
respond_with(@locations)
end
def show
respond_with(@location)
end
def new
@location = Location.new
respond_with(@location)
end
def edit
end
def create
if params[:location].blank?
@location = request.location
@locations = Location.near([current_user.latitude, current_user.longitude], 50, :order => :distance)
end
respond_with(@location)
end
Актуализирано:
ActiveRecord::Schema.define(version: 20150507160846) do
create_table "locations", force: true do |t|
t.string "address"
t.float "latitude"
t.float "longitude"
t.datetime "created_at"
t.datetime "updated_at"
t.string "user_id"
t.string "integer"
end
create_table "posts", force: true do |t|
t.text "post"
t.string "location"
t.string "tag_list"
t.boolean "active"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
end
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
t.string "location"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts
has_many :locations
end