我正在使用 Rails 4.4.1、Ruby 2.1.2、RGeo 0.3.20 和 activerecord-mysql2spatial-adapter 0.4.3
我的问题可能非常简单,因为我对 Ruby 和 Rails 都是新手,但到目前为止我在网络上找不到任何有用的东西。
我想创建一个表单来在我的数据库中插入地理空间坐标,但我不知道如何访问 :latlon 字段 x 和 y。这是我的暂定代码:
<h1>Inserimento nuova Città</h1>
<%= form_for @city, url: cities_path do |city| %>
<p>
<%= city.label :name, "Nome"%><br>
<%= city.text_field :name %>
</p>
<p>
<%= city.label :latlon, "Coordinate GPS" %><br>
<%= city.number_field :latlon.x %><br>
<%= city.number_field :latlon.y %><br>
</p>
<% end %>
访问 localhost:3000/cities/new url 时出现的错误是
undefined method `x' for :latlon:Symbol
有人知道如何创建一个表单来将 latlon.x 和 latlon.y 数据插入我的数据库中吗?
最佳答案
你不能调用 city.number_field :latlon.y
因为这里 :latlon
只是一个符号 - 它告诉助手调用“latlon”方法,并将名称设置为“city[latlon]”。
解决此问题的一种方法是为各个 x/y 值添加 get 和 set 方法。这些可能已经存在,由 gem 添加,我不知道,因为我没有使用过它。但你可以添加
class City < ActiveRecord::Base
def latlon_x
self.latlon.x
end
def latlon_y
self.latlon.y
end
def latlon_x=(num)
self.latlon.x = num
end
def latlon_y=(num)
self.latlon.y = num
end
现在你可以用你的形式说,
<%= city.number_field :latlon_x %><br>
<%= city.number_field :latlon_y %><br>
这将使用latlon_x
来获取值,并会导致latlon_x=
在您执行@city.update_attributes(params[:city]时被调用)
在您的更新操作中。
关于ruby-on-rails - Rails 中使用 form_for 进行纬度/经度坐标插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24082392/