【问题标题】:Extract object from rails dropdown and pass value to javascript从 rails 下拉列表中提取对象并将值传递给 javascript
【发布时间】:2019-07-18 11:05:06
【问题描述】:

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

位置

  • id:整数
  • 姓名:字符串
  • 纬度:十进制 {:precision => 8, :scale => 4}
  • longitude:decimal {:precision => 8, :scale => 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 添加一个地图并显示开始和结束位置的标记,之前我使用下面的代码将数据从我的控制器传递到视图并允许它被 JQuery 访问生成地图

<%= 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 %>

【问题讨论】:

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


    【解决方案1】:

    我建议使用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
    

    我为控制器中的所有路径选择 lat 和 long:

    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>
    

    【讨论】:

    • 快速提问,当我尝试创建路径“开始必须存在开始不能为空白”时出现以下错误
    • 能否分享您创建路径的代码示例?
    • 我在问题中添加了这个
    • 我已经更新了答案(我更改了
    • def create @path = Path.new(path_params) ... def path_params params.require(:path).permit(:start_id, :finish_id) end edgeguides.rubyonrails.org/…
    猜你喜欢
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    相关资源
    最近更新 更多