编辑表单中的序列化哈希值? [英] Edit a serialized hash in a form?

查看:99
本文介绍了编辑表单中的序列化哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在序列化存储在表的settings字段中的哈希,并希望能够在表单字段中编辑该哈希.

I'm serializing a hash that is stored in a settings field in a table, and would like to be able to edit that hash in a form field.

class Template < ActiveRecord::Base
  serialize :settings
end

但是我只是执行<%= f.text_area :settings %>,然后文本区域仅显示序列化的数据而不是哈希.

But I just do <%= f.text_area :settings %> then the text area just shows the serialized data instead of the hash.

如何使哈希显示在文本区域?

How can I get the hash to show in the text area?

推荐答案

也许可以为模型设置另一个访问器.

Maybe setting up another accessor for your model would work.

class Template < ActiveRecord::Base
  serialize :settings
  attr_accessor :settings_edit

  before_save :handle_settings_edit, :if => lambda {|template| template.settings_edit.present? }

  def settings_edit
    read_attribute(:settings).inspect   # should display your hash like you want
  end

  protected
    def handle_settings_edit
      # You may want to perform eval in your validations instead of in a 
      # before_save callback, so that you can show errors on your form.
      begin
        self.settings = eval(settings_edit)
      rescue SyntaxError => e
        self.settings = settings_edit
      end
    end  
end

然后在您的表单中使用<%= f.text_area :settings_edit %>.

Then in your form use <%= f.text_area :settings_edit %>.

我没有测试任何代码,但是从理论上讲它应该可以工作.祝你好运!

I have not tested any of this code, but in theory it should work. Good luck!

警告:像这样使用eval是非常危险的,在此示例中,用户可以在编辑框Template.destroy_all中用一行删除整个模板表.如果涉及到用户输入,请使用其他方法将字符串转换为哈希.

WARNING: Using eval like this is very dangerous, in this example a user could delete the entire Template table with one line in the edit box Template.destroy_all. Use a different method to convert the string to a hash if user input is involved.

这篇关于编辑表单中的序列化哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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