存储动态表单中的数据

时间:2011-06-15 07:31:33

标签: ruby-on-rails ruby forms activerecord dynamic-forms

我正在研究动态表单生成器。有人可以创建如下字段:字符串,文本,布尔值,数字,文件等。

是否存在用于存储此类动态表单数据的宝石或指南?

我的意思是我可以为每种数据类型创建一些表,或者我可以将它们全部存储为TEXT,其中包含应转换的标记类型。

UPD

或者我最好在这里使用nosql?

2 个答案:

答案 0 :(得分:5)

我相信Mongodb是这个应用程序的正确选择,因为它不强制执行任何架构,它是任意数据的理想选择。

同样,它确实支持您所期望的所有数据类型。这很容易。

有一个类似于此的表单集合(Ruby Mongoid代码)

  class XForm
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Paranoia

       field :name, :type => String
       field :user, :type => BSON::ObjectId     

       embeds_many :formfields
  end

 class Formfields
  include Mongoid::Document

     field :name, :type => String
     field :kind, :type => String
     #field :value, :type => String -> dont add it in formfields, make it dynamic sine the type varies

  embedded_in :xform
  end

要将值字段添加为动态字段,您需要在mongoid.yml中启用allow_dynamic_fields: true

并创建一个像这样的新字段

  form = XForm.new(:name=>'test form',:user => current_user.id)
   #for integer field
   form.formfields << Formfields.new(:name => "Age",:kind=>"Integer", :value => 21)
   #for bool field
   form.formfields << Formfields.new(:name => "isMarried",:kind=>"Boolean",:value => true)
   #for string field
   form.formfields << Formfields.new(:name => "name",:kind=>"String",:value => "ram")

希望这有帮助

答案 1 :(得分:2)

我喜欢这种方法。

class User < ActiveRecord::Base
  [:field_1, :field_2, :field_3].each do |method|
    define_method method do
      workable_arbitrary_content[method]
    end

    define_method "#{method}=" do |value|
      data = workable_arbitrary_content.merge(method => value)
      self.arbitrary_content = YAML.dump(data)
    end
  end

  private
    def workable_arbitrary_content
      YAML.load(arbitrary_content || "") || {}
    end
end

在这种情况下,您创建了3个正在保存为YAML的虚拟字段。 在名为users的{​​{1}}中创建一个 text 类型的字段。

以下是上述代码的一些规范。

arbitrary_content