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

Sorry if this was asked and somewhere fully answered. Not sure if I'm looking for the right Rails for this question.

I would like to create a Rails form based on the fields stored in the database. This is what my models look like.

class Field < ActiveRecord::Base belongs_to :form end class Form < ActiveRecord::Base has_many :fields end 

The field model is very simple right now with the type: string and required: boolean columns. Name is the name of the control that I would like to create (text box, check box, radio book). Ideally, I would like to do something like this:

 <%= form_for [something here] do |f| %> <% @fields.each do |field| %> <%= field.type %><br /> <% end %> <% end %> 

I am trying to find a way to replace the string <% = field.type%> with a tag that will correctly display field.type.

Is it possible? Would I be better off using a payload column in a field model storing field types and values ​​like json / xml?

+8
ruby ruby-on-rails
source share
1 answer

As @TuteC mentioned, you can use the .send method to dynamically call each field if you save the type:

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

All Articles