collection_select截断

时间:2011-05-11 23:49:24

标签: ruby-on-rails-3 truncate

如何截断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'} ) %>

2 个答案:

答案 0 :(得分:5)

选项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'}) %>

答案 1 :(得分:1)

我通过将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发送代码块。