2009-10-02 107 views
1

在 「創建方法」 我使用的參數名稱即:名稱=> PARAMS [:名稱]Ruby on Rails的 - 截斷參數

我已通過添加用於截斷在HTML:最大長度和:尺寸限制名

的長度,但在HTML截斷可以容易地跳過,所以我想知道的代碼 「截斷參數:名稱=> PARAMS [:名稱]在控制器」

PL建議的容易程度的一些代碼

回答

1

你可以這樣做:

:name => params[:name][0..15] 

15是你想要多少個字符限制,直到(所以這將是總共16個)。

例子:

>> lipsum = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." 
=> "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." 
>> lipsum[0..10] 
=> "Lorem Ipsum" 
4

我建議你的ActiveRecord這樣validations

這將讓你的代碼更加清晰,你可以很容易地向用戶提供的反饋,它是一個單一的代碼行然後在你的應用程序出現的任何地方處理它,例如:

validates_length_of :name, :maximum => 15