[英]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. 我正在使用Rails 3.2,我需要使用表单生成器对象在标签中显示字段的值。 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. 在上面的f是我的表单构建器,我的模型有一个名为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. 上面的行最后显示“Key Name”作为标签,而我想将key_name的值设置为标签的值,例如。 it should generate a html as <label>Description</label>
where 'Description' is the value of the :key_name
. 它应该生成一个html作为<label>Description</label>
其中'Description'是: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. 然后我还必须在key_name上写一个case语句,这也不起作用,因为我不知道如何从:keyname
字段中提取值。 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: 这是OP在评论中的正确答案:
<%= 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. #{:key_name}
将评估为字符串':key_name'
,然后是正在打印的字符串。 You need to call the method key_name
on your model instance, like: 您需要在模型实例上调用方法 key_name
,如:
<%= f.label :key_name, @model.key_name %>
The same can be done with less code: 使用更少的代码可以完成同样的事情:
<%= f.object.key_name %>
unless insisted on the HTML label tag. 除非坚持使用HTML标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.