3

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

是否有任何宝石或指南来存储来自此类动态表单的数据?

我的意思是我可以为每种数据类型创建许多表,或者我可以将它们全部存储为TEXT应该转换的带有标志的类型。

UPD

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

4

2 回答 2

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

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

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

  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")

希望这可以帮助

于 2011-06-15T09:37:31.650 回答
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在被调用中创建一个textarbitrary_content类型的字段。

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

describe User do
  context "virtual fields" do
    before(:each) do
      @user = User.new
    end

    it "should be able to handle strings" do
      @user.field_1 = "Data"
      @user.field_1.should eq("Data")
    end

    it "should be able to handle integers" do
      @user.field_2 = 1
      @user.field_2.should eq(1)
    end

    it "should be able to handle symbols" do
      @user.field_3 = :symbol
      @user.field_3.should eq(:symbol)
    end

    it "should be possible to override a field" do
      @user.field_3 = :symbol
      @user.field_3 = "string"

      @user.field_3.should eq("string")
    end

    it "should be possible to set more then one field" do
      @user.field_1 = :symbol
      @user.field_2 = "string"

      @user.field_1.should eq(:symbol)
      @user.field_2.should eq("string")
    end
  end
end
于 2011-06-15T09:00:43.503 回答