javascript - 从 Rails 下拉列表中提取对象并将值传递给 JavaScript

标签 javascript jquery mapbox ruby-on-rails-6

我正在创建一个迷你导航应用程序,我有 2 个模型(位置、路径),其中包含以下详细信息

位置

  • id:整数
  • 名称:字符串
  • 纬度:十进制 {: precision => 8, :scale => 4}
  • 经度:十进制{:精度 => 8,:刻度 => 4}

路径

  • 开始:整数
  • 结束:整数

在创建路径的表单上,我有 2 个下拉列表,它们是从位置列表中填充的

<div class="field">
    <%= form.label :start %>
    <%= collection_select(:path, :start, Location.all, :id, :Name, prompt: true) %>
</div>

<div class="field">
    <%= form.label :end %>
    <%= collection_select(:path, :end, Location.all, :id, :Name, prompt: true) %>
</div>

下面我想使用 MapBox 添加 map 并显示开始和结束位置的标记,之前我使用以下代码将数据从我的 Controller 传递到 View 并允许它被 JQuery 访问生成 map

<%= content_tag :div, class: "temp_information", data: {lat: @location.Latitude,long: @location.Longitude} do %>
<% end %>

<script>
map code
$('.temp_information').data('lat')
$('.temp_information').data('long')
</script>

如何从每个选定位置提取纬度和经度并使其可供 JavaScript 使用?

编辑 - 添加路径表单的代码

<%= form_with(model: path, local: true) do |form| %>
<% if path.errors.any? %>
    <div id="error_explanation">
    <h2><%= pluralize(path.errors.count, "error") %> prohibited this path from being saved:</h2>

    <ul>
        <% path.errors.full_messages.each do |message| %>
        <li><%= message %></li>
        <% end %>
    </ul>
    </div>
<% end %>

<div class="form-group">
    <%= form.label :start %>
    <%= form.select :start_id, options_for_select(Location.all.map{ |l| [l.Name, form.object.start_id, { data: { latitude: l.Latitude, longitude: l.Longitude } }] }), { prompt: true }, { class: "form-control" } %> 
</div>

<div class="form-group">
    <%= form.label :end %>
    <%= form.select :finish_id, options_for_select(Location.all.map{ |l| [l.Name, form.object.finish_id, { data: { latitude: l.Latitude, longitude: l.Longitude } }] }), { prompt: true }, { class: "form-control" } %>
</div>


<div class="form-group">
    <%= form.label :minutes %>
    <%= form.number_field :minutes, class: "form-control" %>
</div>

<div class="actions">
    <%= form.submit %>
</div>
<% end %>

最佳答案

我建议使用gon gem用于将数据从 ruby​​ 传递到 javascript。

我写了这样的代码:

# 20190718113356_create_locations.rb
class CreateLocations < ActiveRecord::Migration[5.2]
  def change
    create_table :locations do |t|
      t.string :name
      t.decimal :latitude, precision: 10, scale: 6
      t.decimal :longitude, precision: 10, scale: 6

      t.timestamps
    end
  end
end
# 20190718113423_create_paths.rb
class CreatePaths < ActiveRecord::Migration[5.2]
  def change
    create_table :paths do |t|
      t.references :start, index: true, foreign_key: { to_table: :locations }
      t.references :finish, index: true, foreign_key: { to_table: :locations }

      t.timestamps
    end
  end
end
# location.rb
class Location < ApplicationRecord
  has_many :start_paths, class_name: 'Path', foreign_key: 'start_id', dependent: :destroy
  has_many :finish_paths, class_name: 'Path', foreign_key: 'finish_id', dependent: :destroy

  validates :name, :latitude, :longitude, presence: true
end
# path.rb
class Path < ApplicationRecord
  belongs_to :start, class_name: 'Location', foreign_key: 'start_id'
  belongs_to :finish, class_name: 'Location', foreign_key: 'finish_id'

  validates :start, :finish, presence: true
end
# seeds.rb
Location.destroy_all

10.times do |t|
  Location.create!(
    name: SecureRandom.uuid,
    latitude: rand(-90.000000000...90.000000000),
    longitude: rand(-180.000000000...180.000000000)
  )
end


15.times do |t|
  Path.create!(
    start: Location.order("RANDOM()").first,
    finish: Location.order("RANDOM()").first
  )
end

我为 Controller 中的所有路径选择纬度和经度:

gon.paths = Path.all.preload(:start, :finish).map{ |p| {start: { latitude: p.start.latitude, longitude: p.finish.latitude }, finish: { latitude: p.start.latitude, longitude: p.finish.latitude } } }
p = Path.first
gon.path = {start: { latitude: p.start.latitude, longitude: p.finish.latitude }, finish: { latitude: p.start.latitude, longitude: p.finish.latitude } }

并在 JavaScript 中显示路径

alert(JSON.stringify(gon.paths))
alert(JSON.stringify(gon.path))

如何在 JavaScript 中查找数据

<%= form_for Path.new, url: '' do |form| %>
  <div class="field">
    <%= form.label :start_id %>
    <%= form.select :start_id, options_for_select(Location.all.map{ |l| [l.name, l.id, { data: { latitude: l.latitude, longitude: l.longitude } }] }), { selected: form.object.start_id, prompt: true }, { class: 'startSelect' } %>
  </div>
  <br /><br />
  <div class="field">
    <%= form.label :end_id %>
    <%= form.select :finish_id, options_for_select(Location.all.map{ |l| [l.name, l.id, { data: { latitude: l.latitude, longitude: l.longitude } }] }), { selected: form.object.finish_id, prompt: true }, { class: 'endSelect' } %>
  </div>
<% end %>
<script type="text/javascript">
  $(function() {
    $(".startSelect").change(function() {
      alert(JSON.stringify(['startSelect changed', { latitude: $(this).find(':selected').data('latitude'), longitude: $(this).find(':selected').data('longitude') }]));
    });

    $(".endSelect").change(function() {
      alert(JSON.stringify(['endSelect changed', { latitude: $(this).find(':selected').data('latitude'), longitude: $(this).find(':selected').data('longitude') }]));
    });
  });
</script>

关于javascript - 从 Rails 下拉列表中提取对象并将值传递给 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57093065/

相关文章:

javascript - 获取表中带有复选框的行

javascript - 使用下拉列表中的值通过 jQuery 更改设置 setInterval

jQuery 城市选择器?

javascript - php变量中的Sava html attr

jquery - 使用 google OAuth 2.0 成功登录后无法获取用户信息

ios - 如何将自定义属性从 Mapbox 注释传递到其标注 View ?

javascript - 如何格式化我的 api 调用以在 google 电子表格中发布?

javascript - 从 mapbox 隐藏子层名称链接,然后在单击其父层时使其可见

android - 如果有人深入我的应用程序代码文件和内存并找到了我的 Mapbox 的访问 token key 怎么办?

JavaScript:迭代日期