Rails form to edit JSON object as text

你。 提交于 2020-01-14 06:25:11

问题


I'd like to make a form that lets a user edit one field of a mongoid object as rendered JSON text. There's a field in the model that my rails app should not understand, but I want to expose a generic editor. So for this field, I'd like to render it as pretty JSON, and expose it in a big <textarea> and then parse the JSON back in after any edits.

I can think of a dozen ways to do this, but I'm wonder what would be most consistent with Rails philosophy and least divergent from normal scaffolding. Should I render the object to JSON text in the controller? Then I'd have to repeat that code in the new and edit methods, and the parsing code in the update and create methods, which seems a bit kludgy. Is there a way to define a helper or custom form widget that goes in the _form.html.erb that is more reusable? Or maybe one already written?


回答1:


You can make your own attribute writer/reader, in the model:

  attr_accessible the_field_raw

  def the_field_raw
    self.the_field.to_s
  end

  def the_field_raw=(value)
    self.the_field = JSON(value)
  end

whitch should be compatible with form generators and no extra code in the controllers.

Hope it helps!




回答2:


Serialize the values as JSON.

class Price < ActiveRecord::Base
   serialize :values, JSON

   validates :start, :end, :values, :presence => true
end


来源:https://stackoverflow.com/questions/14288650/rails-form-to-edit-json-object-as-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!