Ruby-on-rails 在 RoR 的文本字段中设置最大长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16166657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:51:23  来源:igfitidea点击:

Set maximum length in Text field in RoR

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-3.2

提问by divz

Has anyone managed to set maximum field lenghts for text fields

有没有人设法为文本字段设置最大字段长度

How can i set the maximum length of a text field. Here is the code iam using

如何设置文本字段的最大长度。这是我使用的代码

<%= text_field_tag(:create_text), :input_html => {:maxlength => 15, :size => 40}  %>

but I cannot seem to set the max number of characters that can be typed into the field.

但我似乎无法设置可以输入到该字段中的最大字符数。

回答by M. Cypher

Here is how you can do it:

您可以这样做:

<%= text_field_tag 'create_text', nil, :maxlength => 15, :size => 40 %>

Source: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-text_field_tag

来源:http: //api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-text_field_tag

回答by Dan Barron

In the text_field_tagcall:

text_field_tag调用中:

:sizerelates to the physical length of the text box. It will be big enough to allow that many characters to be visible in the box. But the user can still enter more.

:size与文本框的物理长度有关。它将足够大以允许在框中可见这么多字符。但用户仍然可以输入更多。

:maxlengthis the maximum number of characters the user can enter, regardless of the physical size of the text box. The text box can be bigger or smaller, but if you set :maxlength => 5, they will only be able to enter 5 characters.

:maxlength是用户可以输入的最大字符数,与文本框的物理大小无关。文本框可以更大或更小,但如果你设置:maxlength => 5,他们将只能输入5个字符。

If this is a hard limit you want for the data in the database, too, you should set a validation. This prevents you from, for example, setting it to more characters in your Rails code.

如果这也是您希望对数据库中的数据进行硬性限制,则您应该设置验证。例如,这可以防止您在 Rails 代码中将其设置为更多字符。

validates_length_of :column_name, :maximum => 5

Finally, for a belts and suspenders approach and to prevent even code that goes against the database from setting a bad value, you can enforce it at the database level. In some cases, other code than your Rails app might update the database. This prevents bad data even in this case.

最后,对于腰带和吊带方法并防止甚至违反数据库的代码设置错误值,您可以在数据库级别强制执行它。在某些情况下,Rails 应用程序以外的其他代码可能会更新数据库。即使在这种情况下,这也可以防止不良数据。

Adding a column in a migration you do it like this:

在迁移中添加一列,您可以这样做:

add_column :table_name, :column_name, :string, :limit => 30

回答by vidur punj

 <%= text_field_tag :"description", '', maxlength: 5   %>
<input type="text" name="description" id="description" value="" maxlength="5">

回答by Dinesh

you can try this

你可以试试这个

<%=text_field_tag 'create_text',:size=>40 %>