Search code examples
ruby-on-rails-3jsonformsmongoid

Rails form to edit JSON object as text


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?


Solution

  • 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!