Rails表单将JSON对象编辑为文本 [英] Rails form to edit JSON object as text

查看:141
本文介绍了Rails表单将JSON对象编辑为文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一种表单,使用户可以将蒙古型对象的一个​​字段编辑为呈现的JSON文本.我的Rails应用程序不应该理解模型中的一个字段,但是我想公开一个通用编辑器.因此,对于此字段,我想将其呈现为漂亮的JSON,并在大的<textarea>中公开它,然后在进行任何编辑后将JSON解析回去.

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.

我可以想到许多方法来实现此目的,但是我想知道哪种方法最符合Rails的原理,而与常规脚手架的差异最小.我应该在控制器中将对象呈现为JSON文本吗?然后,我必须在newedit方法中重复该代码,并在updatecreate方法中重复分析代码,这似乎有点笨拙.有没有一种方法可以定义在_form.html.erb中使用的可重用的帮助程序或自定义表单小部件?或者也许已经写过?

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?

推荐答案

您可以在模型中创建自己的属性writer/reader:

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.

希望有帮助!

这篇关于Rails表单将JSON对象编辑为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆