首页 > 解决方案 > 从 Rails 助手或控制器调用刺激控制器中的函数?

问题描述

我正在开发一个 Rails 应用程序,我想在其中使用 Javascript 的导航 API 来获取用户的地理位置。我在“app/javascript/location_controller”下的控制器中有代码,它可以工作。

import { Controller } from "stimulus"

export default class extends Controller {
    connect(){
        this.getUserLocation()
    }

    getUserLocation(){
        if (navigator.geolocation) {
           navigator.geolocation.getCurrentPosition((position) => console.log(position.coords), (error)=> console.log(error));
        } else {
            alert("Could not get your current location! Please allow location services for RiseUp.")
        }
    }
}

我将如何从 Rails Helper 调用“getUserLocation”?

标签: ruby-on-railsstimulusjs

解决方案


Stimulus 控制器,通常是任何 javascript,不是由您的 ruby​​ 服务器运行,而是由用户的浏览器运行。

如果您想从中获取值,则需要进行一些 ajax 调用,并从普通的 rails 控制器中获取。

就像是:

async getUserLocation() {
  let data = new FormData();
  let position = await navigator.geolocation.getCurrentPosition();
  data.set('position', position);
  await fetch('/api/notify_location', {method: 'POST', body: data, credentials: true});
}

你必须在后端路由它:

scope 'api' do
  post 'notify_location' => 'location#notify'
end

并将其放入控制器中

class LocationController < ApplicationController
  def notify
    # do as needed, you will be able to get the session here
    # because the fetch function was passed credentials: true
    # but beware, this request won't match `request.xhr?` because
    # fetch is not XMLHTTPRequest.

推荐阅读