如何限制Sinatra / Active Record中数据库字符串值的字符/单词数? [英] How to limit character/word count on database string value in Sinatra/Active Record?

查看:119
本文介绍了如何限制Sinatra / Active Record中数据库字符串值的字符/单词数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 ActiveRecord 数据库中有一列,我希望有一定的字数限制。

I have a column in my ActiveRecord database that I want to have a certain word limit.

基本上,我创建了一个允许用户输入文本(字符串)的表单。我想限制该字符串中允许的字符数。

Essentially, I've created a form that allows users to enter text(string). I want to limit the amount of characters that are allowed in that string.

@allposts = Post.limit(20)

这是我到目前为止在 / current 页面的get方法中所拥有的内容,该页面发布了所有内容。 20 =显示的帖子数。

This is what I have so far in the get method for the /current page that posts all of content. 20 = number of posts shown.

我还有一个 / new 页面,用户可以在其中发布新内容。

I also have a /new page where users will post new content.

推荐答案

您可以通过几种不同的方式限制字符数:

You can limit the number of characters in a few different ways:

1。定义您创建的HTML字段的限制:

1.Defining the limit of the HTML field you create:

<input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />

通过更改maxlength属性。从此处获取的示例。

by changing the maxlength attribute. Example taken from here.

2。在用户模型中使用validates选项:

2.Using the validates option in the user model:

validates :attribute_you_want_to_limit, length: { maximum: 50 }

您可以找到有关此选项的更多信息此处

You can find more about this option here.

3。在模式:

t.string :your_attribute, :limit => 20

第一个选项不允许用户在该字段中输入更多内容,第二个选项不允许保存对象,第三个选项不允许将属性保存到数据库。

The first option won't allow the user to input any more in the field, the second won't allow saving the object and the third option won't let the attribute get saved to the database.

我建议使用第二个选项。

I recommend the second option.

您还可以通过几种不同的方式使用Javascript,中输入。有关如何操作的很好解释。

You can also use Javascript in a few different ways, here's a good explanation on how to.

这篇关于如何限制Sinatra / Active Record中数据库字符串值的字符/单词数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆