sqlruby-on-railspostgresqltextcharacter-limit

Rails/PostgreSQL: Adding character limit to text


I want to implement a character limit to a data value on my PostgreSQL database for my Ruby on Rails application. Currently my database table looks like this:

create_table "applications", force: :cascade do |t|
    t.string   "name"
    t.string   "gender"
    t.date     "date_of_birth"
    t.string   "gpa"
    t.text     "essay"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
end

I want to change it so the "essay" only allows 10000 characters. From my limited understanding of PostgreSQL, text is unlimited by default whereas string is for 255 characters or less. I thought about implementing a Javascript conditional to not let the user hit the submission button in the client if the text is over 1,000 characters, but of course a tech savvy user could change that. What would be the most optimal way to do this?


Solution

  • Use rails model validations - validates_length_of.

    On the rails end you can add this in application.rb file

    validates_length_of :essay, :maximum => 1000

    This will ensure that max size is not exceded. Also keep the javascript validation, since its helpful for all users except the malicious once.

    Also I recommend you to change the table name from applications. You can get easily confused