Skip to content

Commit 79fa6aa

Browse files
authored
Skip validations on legacy primary keys like we do for omakase 'id's. (joshwlewis#71)
1 parent 3a3bdeb commit 79fa6aa

File tree

5 files changed

+21
-1
lines changed

5 files changed

+21
-1
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
.bundle/
2+
.byebug_history
23
*.gem
34
log/*.log
45
pkg/

lib/validates_by_schema.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def schema_validatable_columns
6262
end
6363

6464
def ignored_columns_for_validates_by_schema
65-
['id', 'created_at', 'updated_at', 'deleted_at']
65+
[primary_key, 'created_at', 'updated_at', 'deleted_at']
6666
end
6767

6868
end

spec/config/schema.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,15 @@
3030
t.boolean 'enabled'
3131
t.binary 'data'
3232
t.integer 'parent_id', null: false
33+
t.integer 'legacy_id', null: false
3334
t.integer 'other_id'
3435
t.integer 'kind', null: false
3536
t.string 'list', ENV['DB'] == 'postgresql' ? { array: true, limit: 3 } : {}
3637

3738
t.index 'parent_id'
3839
t.index ['name', 'wheels'], unique: true
3940
t.index 'other_id', unique: true
41+
t.index 'legacy_id', unique: true
4042
t.index ['doors'], unique: true, where: 'enabled = true'
4143
t.index ['model', 'price'], unique: true
4244
t.index ['model', 'cost'], unique: true
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
require 'contraption'
2+
3+
class LegacyContraption < Widget
4+
self.primary_key = :legacy_id
5+
self.clear_validators!
6+
validates_by_schema # recalculate the validations
7+
end

spec/validations_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
enabled: true,
2121
data: 'the question'.unpack('b*').to_s,
2222
parent: Widget.new,
23+
legacy_id: 0,
2324
kind: 'one',
2425
list: ['abc']
2526
}
@@ -135,6 +136,15 @@
135136
end
136137
end
137138

139+
context 'legacy objects' do
140+
subject { LegacyContraption.new attributes.merge(id: 1, legacy_id: nil) }
141+
142+
context 'should skip validations on a custom primary key while applying them to the ID' do
143+
it { should validate_presence_of(:id) }
144+
it { should_not validate_presence_of(:legacy_id) }
145+
end
146+
end
147+
138148
context 'validates uniqueness' do
139149
let(:valid_attributes) do
140150
attrs = attributes.dup

0 commit comments

Comments
 (0)