开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜