以形式坐标数组

时间:2012-09-07 21:35:06

标签: ruby-on-rails ruby ruby-on-rails-3 erb

我有一个用于创建地址的表单,该地址有一个坐标数组。但我不知道生成输入以键入例如3坐标。可以是n坐标,我正在计划使用jQuery(创建输入)。但是现在我想显示现有的坐标。

以下是代码:

模型

class Address
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Spacial::Document

    field :street, :type => String
    field :number, :type => Integer

    field :phone, :type => String

    field :delivery_zone, :type => Array
end

erb.html

<%= form_for [:owner, :company,@address], :html => {:class => "form-horizontal"} do |f| %>
  <%= @address.delivery_zone.each do |dz|%>
    <% fields_for 'delivery_zone[]' , dz do |items| -%>

        ?? I don't know what to write here!!

    <% end %>
  <% end %>
<%end%>

我正在寻找的是为字段delivery_zone和数组中的每个项生成如下内容:

<input id="address_delivery_zone[]"  name="address[delivery_zone][]" type="text" value="32.7 33.8" />

1 个答案:

答案 0 :(得分:2)

我对Mongoid和Mongoid :: Spacial并不熟悉,但我会尽力帮助。

我理解你的问题,你需要每个address可能有多个delivery_zones,我认为这是地理坐标。我认为最好做一些事情:

class Address
  include Mongoid::Document
  include Mongoid::Timestamps

  field :street, :type => String
  field :number, :type => Integer
  field :phone, :type => String

  embeds_many :delivery_zones
  accepts_nested_attributes_for :delivery_zones
end

class DeliveryZone
  include Mongoid::Spacial::Document

  embedded_in :address
  field :coordinates, :type => Array, :spacial => true

  # accessors will help us manipulate the coordinates
  def latitude
    coordinates[:lat] # or coordinates[1] if you use the array
  end

  def longitude
    coordinates[:lng] # or coordinates[0] if you use the array
  end

  def latitude=( lat )
    coordinates[:lat] = lat
  end

  def longitude=( lng )
    coordinates[:lng] = lng
  end
end

然后你可以使用form_forfields_for,因为它打算使用嵌套资源,我认为(不保证按原样工作)应该是这样的:

<%= form_for @address do |address_form| %>
  <% @address.delivery_zones.each do |zone| %>
    <%= address_form.fields_for( zone ) do |zone_form| %>
       <p>Latitude :</p> 
       <p><%= zone_form.text_field :latitude %></p>
       <p>Longitude :</p> 
       <p><%= subform.text_field :longitude %></p>
  <% end %>
<% end %>

有关嵌套资源表单的详细信息,请访问railscasts #197railscasts #75