I am using Rails 3.2 and am in need to display the value of a field in a label using a form builder object. Displaying it in a text box is straight forward but I am not able to do it in a label. the code is something like this:
<%= f.label :key_name, "#{:key_name}"%>
<%= f.text_field :key_name %>
In the above f is my form builder and my model has a field called key_name. The second line works fine in which I display it inside a text field while the first line does not. How do I do it. The line above ends up displaying "Key Name" as the label while I want the value of key_name to be set as the value of the label eg. it should generate a html as <label>Description</label>
where 'Description' is the value of the :key_name
.
I also then have to write a case statement upon the key_name which also does not work because I dont know how to extract the value from the :keyname
field. something like this:
<% case :key_name %>
<% when 'Description' %>
... do something
To help anyone that would otherwise miss it. Here's OP's correct answer in the comments:
<%= f.label :key_name, f.object.key_name %>
#{:key_name}
is going to evaluate to the string ':key_name'
, which is then what is being printed. You need to call the method key_name
on your model instance, like:
<%= f.label :key_name, @model.key_name %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With