我找不到如何在Rails中显示动态标签,我尝试使用:value => show_name
属性但它不起作用,它只显示Show name
。这是视图代码
<p>
<div class="control-group">
<%= f.label :show_name, :value => :show_name, :class => 'control-label' %>
<%= #this next line fails with undefined method `show_name' for #<ActionView::Helpers::FormBuiler>
#f.label f.send :show_name, :class => 'control-label'
%>
<div class="controls">
<%= f.text_field :variable_value, :class => 'text_field' %>
<%= f.hidden_field :variable_id, :class => 'text_field' %>
<%= f.hidden_field :show_name, :class => 'text_field' %>
</div>
</div>
<p>
如果需要,这里是我模型中的show_name定义。
def show_name
Variable.find_by_id(self.variable_id).name
end
答案 0 :(得分:1)
好的,所以我最终找到一个非常DRY
的解决方案,感谢this post。我要做的唯一事情就是解释一下该怎么做:
首先,我们将假设我们有嵌套表单的最复杂的情况,因此我们在fields_for
方法中使用form_for
:
<!-- f represents the form from `form_for` -->
<%= f.fields_for :nested_model do |builder| %>
<p>
<div class="control-group">
<!-- here we are just calling a helper method to get things DRY -->
<%= builder.label return_value_of_symbol(builder,:show_name), :class => 'control-label' %>
<div class="controls">
<%= builder.text_field :variable_value, :class => 'text_field' %>
<%= builder.hidden_field :variable_id, :class => 'text_field' %>
</div>
</div>
</p>
<% end %>
请注意,我们在助手的参数中包含了构建器对象(在fields_for调用中指定)。
在我们的帮助器中,我们定义了return_value_of_symbol
函数
def return_value_of_symbol(obj,sym)
# And here is the magic, we need to call the object method of fields_for
# to obtain the reference of the object we are building for, then call the
# send function so we send a message with the actual value of the symbol
# and so we return that message to our view.
obj.object.send(sym)
end
答案 1 :(得分:0)
使用label_tag
,将show_name放在控制器上的实例变量上并使用如下:
<%= label_tag @show_name, nil, :class => 'control-label' %>
编辑:
在application_helper.rb
上,创建一个与此类似的辅助方法:
def show_name(name)
content_tag(:label, name, :class => 'control-label')
end
然后你就可以在你的观点上使用show_name(name)
:
<%= show_name(@name) %>
请记住填充@name variable
。