我正在使用具有登录功能的 RoR 创建一个博客,我希望将每篇文章提交限制为 1,000 个字符,并将任何人的回复评论限制为最多 350 个。我将如何实施甚至开始这个?
理想情况下,字符计数会在添加字符时倒计时,并在负数时改变颜色(如 Twitter)。
或者,
如果用户超出限制,文章或评论会发出闪烁通知。
我认为我实际上可以限制字符计数,在模型中添加以下内容:
validates_length_of :article, :maximum => [第 800
章] 400
它是在用户键入时向用户显示剩余字符数的方法,但现在是在客户端吗?罗尔能做到这一点吗?
I am creating a Blog using RoR with a sign-in feature and I want to limit each article submission to say 1,000 characters and anyone's responding comments to 350 max. How would I implement or even start this?
Ideally the char count will count down when a char is added and change color when in the minus numbers (like Twitter).
or,
The article or comment throws up a flash notification if the user goes over the limit.
Am thinking that I can actually limit the char count adding the following in the model:
validates_length_of :article, :maximum => 800
validates_length_of :comment, :maximum => 400
Its the method of showing the user the remaining char count as they type, but on the client side for now? Can RoR do this?
发布评论
评论(4)
您要求的验证非常简单。
我建议您使用 javascript、jquery 或您选择的任何其他 js 框架在浏览器的客户端实现它们。
如果您在服务器端进行验证,在 Rails 中,您仍然需要将文本字段元素与一些与之关联的 javascript 事件绑定。
因此,如果您想要如此高水平的 UI,请不要在服务器端(此处为 Rails)进行此类验证。
The validations you are asking, are very simple.
I would suggest you to implement them at the client side in the browser using javascript, jquery or any other js framework of your choice.
If you do the validations at the server side, in Rails, you will still need to bind the textfield element with some javascript events associated with it.
So, don't do such validations at server-side(Rails here), if you want such a high level of UI.
您必须在 javascript 中执行此操作,因为您正在寻找的是客户端功能。您还应该进行模型验证,以确保保持此限制(您可以通过使用像curl这样的东西发送POST来轻松绕过javascript验证)。
谷歌搜索“javascript字符计数器”给出了大量结果。
You'll have to do this in javascript, since it's client side functionality that you're looking for. You should also have model validations to ensure this limit is kept (you can get around javascript validations pretty easily by just sending a POST using something like curl).
Googling for "javascript character counter" gives plenty of results.
这是一个实现服务器端验证的解决方案,并且在验证失败时将显示“flash”错误消息。
在您的文章模型中:
在您的 ArticlesController 中:
在您的文章视图中:
Here's a solution that implements server-side validation and that will display a "flash" error message when validation fails.
In your Article model:
In your ArticlesController:
In your Articles view:
通过 jQuery 插件在这里找到了一个很好的“跨浏览器”解决方案,该解决方案将完成这项工作并“阻止”用户在客户端提交超过分配数量的文章。 此处 所需的 Rails 插件是 此处
Found a nice 'cross-browser' solution here via a jQuery plugin that will do the job and 'stop' users from submitting articles over the allocated amount on the client-side. Here The required Rails plugin is Here