如何截断collection_select中的值
<%= collection_select(:standard, :parent_id, Standard.all, :id, :value, {:include_blank => 'No Parent'} ) %>
我想缩短该值,但出现错误:
<%= collection_select(:standard, :parent_id, Standard.all, :id, truncate(:value, :length => 40), {:include_blank => 'No Parent'} ) %>
选项 1:
向模型添加一个自定义方法,例如 truncated_value
,并改用该方法:
class Standard < ActiveRecord::Base
include ActionView::Helpers::TextHelper
def truncated_value
truncate(value, :length => 40)
end
...
...
...
end
那么在您看来:
<%= collection_select(:standard,
:parent_id,
Standard.all,
:id,
:truncated_value,
{:include_blank => 'No Parent'}) %>
选项 2:
只需改用select
标记帮助程序:
<%= select(:standard,
:parent_id,
Standard.all.collect{ |s| [truncate(s.value, :length => 40), s.id] },
{:include_blank => 'No Parent'}) %>
我通过将text_method
传递为proc
解决了这个问题,如下所示:
<%= collection_select(:standard,
:parent_id,
Standard.all,
:id,
proc {|st| st.value.truncate(40)},
{:include_blank => 'No Parent'}) %>
有关更多信息,我注意到collection_select接收值作为text_method
,因此我使用 proc 发送代码块。