A free article written by rails beginners for rails beginners. Recently, my friend's children have been rushing to say "** shit !!!!!!!!", so validation to eliminate the sweet idea that ** shit ** would be interesting. The purpose is to make good use of and not to spread vulgar words to the world.
Rails5
--Run rails new --Create controllers, models and tables, and set routing appropriately.
This time, if a content containing a word (shit) that is not suitable for the content column of the Post model is about to be posted, we will issue a verification error to protect the world of love and peace of service and prevent spreading dirty words. ..
ActiveRecord::Schema.define(version: 2018_06_10_125752) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "posts", force: :cascade do |t|
t.string "title", null: false
t.text "content", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "user_id", null: false
t.index ["user_id"], name: "index_tasks_on_user_id"
end
end
I will register the method for verification.
class Ppst < ApplicationRecord
validate :validate_content_not_including_unko
Those who have studied Rails to some extent here will want to put in a tsukkomi. so! !! !! That there is no ** validate ** in the third person singular present (third person) s ** instead of ** validates **! !! !! !! The difference between the two seems to be either custom or self-made validation.
Apparently, when using custom validation, use ** validate **. .. .. Horrible and difficult to understand https://guides.rubyonrails.org/active_record_validations.html#custom-methods
I will implement a method for verification
class Ppst < ApplicationRecord
validate :validate_name_not_including_unko
private
def validate_content_not_including_unko
errors.add(:content, 'If you write this, you can't! !! !! !!') if content.include?('shit')
end
end
①private Since this method is not used from outside this object, it is described below private
②validate_content_not_including_unko
The job of the validation method is ** "If you find a validation error, put the error content in errors" **.
Therefore, when content.include? ('Unko')
contains shit in the content column, the content of the verification error is included in errors.add.
This will stop you from saying that bad boy. .. ..
There is one thing I thought through this article that it had nothing to do with it.
Instead of making it possible to post suddenly by typing a sentence on Twitter or pressing the post button, to take a breather on the confirmation screen once, "Are you saying or acting like being dried?" I wondered if I could reduce the number of sentences that would be emotionally written and spread some kind of adverse effect.
Also, I'm sorry I had a lot of poop.
Recommended Posts