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

自闭症网瘾萝莉.ら 提交于 2019-12-07 06:05:54

问题


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

回答1:


#{: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 %>



回答2:


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 %>



回答3:


The same can be done with less code:

<%= f.object.key_name %>

unless insisted on the HTML label tag.



来源:https://stackoverflow.com/questions/15927678/display-the-value-of-a-field-using-form-builder-into-a-label-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!