8

I have dynamic form which has a set of values. I created a partial which contains text fields which I display. Next to each of them I would like to display a label containing the title of the text. For instance First Name, and Last Name would not be known previously. How do I go about doing that? It seems that I cannot access the attributes directly. But when I use the label field, the variable name in the label is displayed not the actual value.

sebajb
  • 161
  • 1
  • 4
  • Could you try to explain what you want to accomplish better? Maybe give an example? I have tried to understand in order to help you but I can't understand what you need. – Petros Mar 06 '10 at 17:09
  • I have an object which has a one-to-many relation with a set of Dynamic Fields {Name,Value}. When a user is updating the dynamic fields I want to display the name of the fields as the actual label instead of the hardcoded label. Or a predetermined String value. The dynamic form is inside a partial and all data. Snippets: _form.erb <% f.fields_for :entity_values do |builder| %> <%= render "entity_value_fields", :f => builder%> <% end % _entity_value_fields.erb <%= f.label :name %> {label needs to be the dynamic name of that value} <%= f.text_field :value %> ... – sebajb Mar 06 '10 at 19:39

3 Answers3

6

Well! This was a reflection of how new I am to rails. You can do this by using f.object.{attr_name} and that worked.

Paul Richter
  • 10,908
  • 10
  • 52
  • 85
sebajb
  • 161
  • 1
  • 4
5

f.object.{attr_name} didn't work for me, but f.object[:attr_name] did.

Ben
  • 305
  • 5
  • 12
  • 2
    `f.object.first_name` or `attr_name = 'first_name'; f.object.send(attr_name)` will work. `f.object.{attr_name}` is invalid Ruby syntax. – Kris Nov 21 '12 at 12:18
2

What about:

f.object.send(attr_name)

That would be the Rubyish way.

Kris
  • 19,188
  • 9
  • 91
  • 111
  • Can you explain this better? – KoU_warch Nov 19 '12 at 16:03
  • 2
    All form builders have a method called `object` which returns the object which the form is wrapping, typically an ActiveRecord model, say person. We then call `send` on that person to send it a message, so `person.send(:name)` is the same as `person.name`. As you can see using `send` means we do not need to hardcode the attribute (e.g last_name) which we want to display as our label. So in the above case `attr_name` can be any string, either last_name, first_name, whatever. – Kris Nov 21 '12 at 12:16