How to create a Rails form_for with dynamic form fields from a database table?

ruby, ruby-on-rails

Solution

Like @TuteC mentioned, you can use the .send method to dynamically invoke each field, if you are saving the type:

<%= form_for [something here] do |f| %>
  <% @fields.each do |field| %>
    <%= f.send(field.type.to_sym, field.name) %><br />
  <% end %>
<% end %>

Problem

Sorry if this has been asked and answered in full somewhere. Not sure if I'm searching with the correct Rails speak for this question. I'd like to create a Rails form based on fields stored in the database. Here's what my models looks like so far. ``` class Field < ActiveRecord::Base belongs_to :form end class Form < ActiveRecord::Base has_many :fields end ``` The field model is very simple as of now with type:string and required:boolean columns. Name being the name of the control I'd like to create (textbox, checkbox, radiobutton). Ideally I'd like to do something like this: ``` <%= form_for [something here] do |f| %> <% @fields.each do |field| %> <%= field.type %><br /> <% end %> <% end %> ``` I'm struggling with finding a way to replace the line <%= field.type %> with a tag that would correctly render the field.type. Is this possible? Would I be better off using a payload column in the field model storing field types and values as json/xml?

Original source