Created
September 13, 2017 00:31
-
-
Save hamajyotan/ee40876bd3ecbc2e01e08ab112b3f1d3 to your computer and use it in GitHub Desktop.
NOT NULL 制約の定義されている列に対し、自動的に presence バリデーションを付与
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# NOT NULL 制約の定義されている列に対し、自動的に presence バリデーションを付与します | |
# | |
module AutoPresenceValidation | |
extend ActiveSupport::Concern | |
included do | |
ignore_types = %i[boolean] | |
cols = columns.dup | |
cols.reject!(&:null) | |
cols.reject! { |col| col.name == primary_key } | |
cols.reject! { |col| col.type.in?(ignore_types) } | |
if record_timestamps | |
# タイムスタンプ列名を取得し、それに合致する列定義は対象外とします | |
dummy_ar_instance = Class.new { include ActiveRecord::Timestamp }.new | |
timestamp_attributes = ( | |
dummy_ar_instance.send(:timestamp_attributes_for_create) + | |
dummy_ar_instance.send(:timestamp_attributes_for_update) | |
).map(&:to_s) | |
cols.reject! { |col| col.name.in?(timestamp_attributes) } | |
end | |
cols.each { |col| validates(col.name.to_sym, presence: true) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment