开发者

Rails: best way to generate a form dynamically

开发者 https://www.devze.com 2023-01-08 16:27 出处:网络
I am creating an application where I want to add metadata about table fields from an enterprise system.

I am creating an application where I want to add metadata about table fields from an enterprise system.

I have a table_structure model which retrieves a table definition information like:

table_name
field_name
Field_type
field_length
...

a particular field may exist in multiple tables like:

tableA
fieldX

tableB
fieldX

regardless of table, I want to add attributes to the field so that

fieldX :has_many :attributes

and the attribute model would be

:field
:attribute
:value

I would like to create a single form where I can capture many attributes. I've seen the nested forms railscast and that's close to what I want to do, but I would like to have the form generated dynamically with different input types because the attributes captured may change.

I was thinking of adding this method to the attribute model and somehow iterating through them and generating the form.

  def self.attributes_types
    {'Business Essential' => {:field_type=>:radio,:values=>[:y,:n,nil],:default_value=>nil}}

    {'Owner' 开发者_Python百科=> {:field_type=>:text}}
  end

Is Nested form the way to go? I am not adding fields, just attributes to fields, so I can pass a params[:field] to new and use that for my new attribute(s). Is there another way to create this form?


I think you're on the right track and nested fields for attributes are the way to go. If new attributes are going to be introduced in the future, you might want to store attribute definitions in a database table instead of defining them in the model.


I don't normally recommend document-oriented database systems but this may be a good candidate for MongoDB instead of a traditional SQL backend. Regardless of the backend, nested forms are the way to go. You can build some helpers to dynamically add them to your forms based on the metadata stored in your database.


What your are looking for are called dynamic forms and the answer to your question is answer in 403-dynamic-forms. http://railscasts.com/episodes/403-dynamic-forms https://github.com/railscasts/403-dynamic-forms

Its kinda late but i hope it helps someone else

0

精彩评论

暂无评论...
验证码 换一张
取 消