Skip to content

Instantly share code, notes, and snippets.

@hamajyotan
Created September 13, 2017 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamajyotan/ee40876bd3ecbc2e01e08ab112b3f1d3 to your computer and use it in GitHub Desktop.
Save hamajyotan/ee40876bd3ecbc2e01e08ab112b3f1d3 to your computer and use it in GitHub Desktop.
NOT NULL 制約の定義されている列に対し、自動的に presence バリデーションを付与
# 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