2009-10-02 106 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