正在通过IP(例如Yik Yak)在页面加载时创建用户。我通过getLocation()从我的用户那里获取GPS信息。当然,在我可以存储GPS信息之前正在创建用户,因此lat和lng为空。
SO而不是将其转换为由rails中的方法调用然后保存的cookie,我想要做的是用AJAX POST请求更新用户并更新数据库。
语法方面,如何输入请求以及如何在user_controller中调用它?
由于
以下是我尝试在cookie中执行此操作的代码,但由于我正在使用IP创建onload(如Yik Yak),因此无法正常工作。
application.html.erb
<body onload="getLocation()">
应用。 JS
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setGeoCookie);
console.log("just got geolocation");
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
console.log("can't get geolocation");
}
}
function setGeoCookie(position) {
var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
document.cookie = "lat_lng=" + escape(cookie_val);
}
application_controller.rb
def save_user_location
if cookies[:lat_lng]
@lat_lng = cookies[:lat_lng].split("|")
@user=@current_user
@user.latitude=@lat_lng[0]
@user.longitude=@lat_lng[1]
@user.save
redirect_to users_index_path
end
end
# POST /users
# POST /users.json
def create
save_user_location
@user = User.new
set_current_ip
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
schema.rb
create_table "users", force: :cascade do |t|
t.string "current_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.float "latitude"
t.float "longitude"
end