0

我有一个创建地址的表格,这个地址有一个坐标数组。但我不知道生成输入以键入例如 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" />
4

1 回答 1

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_for并且fields_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

于 2012-09-08T18:30:36.363 回答