Chmen Nalivnik
Chmen Nalivnik

Reputation: 67

How to edit GeoJSON data in rails view?

I want to have ability to edit GeoJSON data as text, in edit page. I use Rails, PostgreSQL with activerecord-postgis-adapter. For encoding data I use rgeo-geojson.

My show view works fine, I encode:

<%= RGeo::GeoJSON.encode(@field.shape, json_parser: :json) %>

But how to upgrade my edit view, so I could edit data in GeoJSON format and save it:

<%= form_for :field, url: field_path(@field), method: :patch do |f| %>
...
  <p>
    <%= f.label :shape %><br>
    <%= f.text_area :shape %>
  </p>
...

<% end %>

Sorry if the question look messy

Upvotes: 2

Views: 454

Answers (1)

Ilya Lavrov
Ilya Lavrov

Reputation: 2860

You may add to Field model a virtual attribute which will convert the postgis db column to GeoJSON and back:

class Field < ActiveRecord::Base
  def shape_text
    RGeo::GeoJSON.encode(shape).to_json
  end

  def shape_text=(text)
    self.shape = RGeo::GeoJSON.decode(text, json_parser: :json)
  end
end


<%= form_for :field, url: field_path(@field), method: :patch do |f| %>
...
  <p>
    <%= f.label :shape_text %><br>
    <%= f.text_area :shape_text %>
  </p>
...

<% end %>

Upvotes: 2

Related Questions