Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 895
Pteranodon_John Avatar asked May 06 '12 12:05

Pteranodon_John


1 Answers

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 %>
like image 153
bruno077 Avatar answered Sep 28 '22 01:09

bruno077