Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the value of a field using form builder into a label in rails

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
like image 352
Vijay Avatar asked Apr 10 '13 13:04

Vijay


2 Answers

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 %>
like image 71
Fellow Stranger Avatar answered Nov 01 '22 23:11

Fellow Stranger


#{: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 %>
like image 23
omnikron Avatar answered Nov 02 '22 00:11

omnikron