I am trying to use a hash to display a form :
PREFIX_STR = "Prefix"
FIRST_STR = "First Name"
NEW_USER_HASH = Hash.new
NEW_USER_HASH[ "prefix" ] = { "label" => PREFIX_STR, "type" => "text_field" }
NEW_USER_HASH[ "first" ] = { "label" => FIRST_STR, "type" => "text_field" }
And in the new.html.erb, I have:
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<% NEW_USER_HASH.each do |column_name,field_info| %>
<div class="field">
<%= f.label field_info["label"] %>
<%= f.text_field column_name %>
</div>
<% end %>
This works fine, but instead of f.text_field, I want that to be what’s in field_info[“type”]. Nothing I tried worked. Any ideas?
Thanks
You might try
f.send(field_into["type"], column_name).(Edited to remove “
to_sym“, which a commenter tells me is unnecessary (I thoughtsendrequired symbols.)Why this works:
some_object.send("hello")is simply another way of writingsome_object.hello. In Ruby, invoking a “method” on an object is actually a form of message passing — you’re sending a message to that object, and the object interprets it as a method invocation (or doesn’t — with ruby metaprogramming something that looks like a method call need not be).In this case, you have an object
fwhich represents aform_helperobject, so when you callf.text_field, you’re sending a message to that object. By usingf.send, you do the same thing, except you can generate the content of that message dynamically.