Ruby on Rails - Truncate参数

时间:2009-10-02 06:35:30

标签: ruby-on-rails

在“创建方法”中我使用参数名称,即:name => PARAMS [:名称]

我在html中使用truncate,添加:maxlength和:size 来限制名称的长度

但是html中的截断可以很容易地跳过,所以我想知道代码 “在控制器中截断参数:name => params [:name]

请建议一些代码

2 个答案:

答案 0 :(得分:5)

我建议您在主动记录validations

中执行此操作

这将使您的代码更加清晰,您可以轻松地向您的用户提供反馈,而这只是一行代码,然后在您的应用程序中出现的任何位置处理此代码,例如:

validates_length_of :name, :maximum => 15

答案 1 :(得分: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"