Dynamically creating the html for forms created by user in application.

In my rails application, a user creates a form by selecting the type
of the data i.e.(string, integer, text) and he then gives input filed
name for it.
i.e. if user wants Name as capition, txtname as input field name and
string as database field type the form will generated as -
<form action="someaction">
Name: <input type="text" name="txtname"></input>
<input type="submit" value="Submit">

So how can create this html from this user given information. Is there
a plugin for this work ?

This is a pretty common use case in lots of applications, and
depending on what sorts of customization you want to allow your users,
you can get quite complex with it if you like. But in the simple
case, you basically want four model classes, divided roughly into a
set of two for the form creators, and two for the users filling out
the forms. Here's an example using your terminology:

UserForm is a form created by a user
FormField is a field on a UserForm, which contains a caption, a type,
and a txtname
UserForm has_many :form_fields

...and, parallel to these, for the users filling out the forms...

FormReply is one instance of a UserForm that's been filled out
ReplyValue is the answer the user gave to a particular FormField
FormReply has_many :reply_values, and belongs_to :user_form
(and UserForm has_many :form_replies)

When generating the HTML for this kind of thing, the key concept to
keep in mind is that what the user's actually doing is _creating a
FormReply_. Thus, the ERB template might look like this:

<%= form_for(@form_reply) do |f| %>
  <%= fields_for :reply_values do |value_fields| %>
    <%= value_fields.text_field :value %>
  <% end %>
  <%= f.submit_tag %>
<% end %>

The above template assumes you've set FormReply to accept nested
attributes for reply_values, and that you're going to populate a blank
set of them in the controller action.

Of course, this is only one way to do it, and I'm sure others have
differing opinions on approaches... :slight_smile:


Ok, now i have implemented something similar to this from database perspective, but not from views and actual html generation thing. Will give try to above idea of for generating actual html using form_for method itself.

Thanks Nat.

On a side note, if your application primarily relies on user generated forms, a documentbased/key-value database might be a better option. I’m talking about databases like MongoDB and the likes.


As mentioned below, the whole stack for implementing dynamic fields in a relational database adds up to 4 or more models. If you want to retrieve all the data, you’ll end up with quite a few joins, which might impact performance quite a bit.