Collection_select truncate

How can I truncate a value in a collection_select

<%= collection_select(:standard, :parent_id, Standard.all, :id, :value, {:include_blank => 'No Parent'} ) %> 

I would like the value to be reduced, but I get errors with this:

 <%= collection_select(:standard, :parent_id, Standard.all, :id, truncate(:value, :length => 40), {:include_blank => 'No Parent'} ) %> 
+4
source share
2 answers

Option 1:

Add a custom method to your model, for example truncated_value , and use this instead:

 class Standard < ActiveRecord::Base include ActionView::Helpers::TextHelper def truncated_value truncate(value, :length => 40) end ... ... ... end 

Then, in your opinion:

 <%= collection_select(:standard, :parent_id, Standard.all, :id, :truncated_value, {:include_blank => 'No Parent'}) %> 

Option 2:

Instead, use the select tag instead:

 <%= select(:standard, :parent_id, Standard.all.collect{ |s| [truncate(s.value, :length => 40), s.id] }, {:include_blank => 'No Parent'}) %> 
+5
source

I solved this problem by passing text_method as proc as follows:

 <%= collection_select(:standard, :parent_id, Standard.all, :id, proc {|st| st.value.truncate(40)}, {:include_blank => 'No Parent'}) %> 

For more information, I notice that collection_select gets the value as text_method , so I send the code block with proc .

+1
source

All Articles