2

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)

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.

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

nadiabcarmon
  • 51
  • 1
  • 6

1 Answers1

1

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

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" />

by changing the maxlength attribute. Example taken from here.

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.Putting a limit in the schema:

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.

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

Viktor
  • 2,623
  • 3
  • 19
  • 28
  • Thanks Viktor. I chose the first method...Which worked perfectly . But will also look into all of the other resources you posted. – nadiabcarmon May 27 '18 at 02:47
  • I would suggest you to have additional security features regarding the length of certain attributes. A maxlength HTML attribute is very easy to bypass and potential users could abuse that. Here's a good explanation : https://security.stackexchange.com/a/16191 – Viktor May 27 '18 at 10:57