问题
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.
回答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.
来源:https://stackoverflow.com/questions/50544860/how-to-limit-character-word-count-on-database-string-value-in-sinatra-active-rec