collection_select truncate
How can i truncate the value in a collection开发者_开发技巧_select
<%= collection_select(:standard, :parent_id, Standard.all, :id, :value, {:include_blank => 'No Parent'} ) %>
I would like to have the value shortened, but am getting errors with this:
<%= collection_select(:standard, :parent_id, Standard.all, :id, truncate(:value, :length => 40), {:include_blank => 'No Parent'} ) %>
Option 1:
Add a custom method to your Model, something like truncated_value, and use that instead:
class Standard < ActiveRecord::Base
  include ActionView::Helpers::TextHelper
  def truncated_value
    truncate(value, :length => 40)
  end
  ...
  ...
  ...
end
Then in your view:
<%= collection_select(:standard, 
                      :parent_id, 
                      Standard.all, 
                      :id, 
                      :truncated_value, 
                      {:include_blank => 'No Parent'}) %>
Option 2:
Just use a the select tag helper instead:
<%= select(:standard, 
           :parent_id, 
           Standard.all.collect{ |s| [truncate(s.value, :length => 40), s.id] },
           {:include_blank => 'No Parent'}) %>
I solved this issue by passing text_method as proc as the following: 
<%= collection_select(:standard, 
                  :parent_id, 
                  Standard.all, 
                  :id, 
                  proc {|st| st.value.truncate(40)}, 
                  {:include_blank => 'No Parent'}) %>
For more info I notice that collection_select receive the value as text_method, so I send block of code using proc.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论