Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add xor check for MTI a la Enterprise Rails, Chapter 10

  • Loading branch information...
commit c7af232fb3c7b75227452db36e62398c57ba8b41 1 parent 1372328
@look look authored
View
2  README.rdoc
@@ -106,6 +106,8 @@ Below is the list of constraints available and tested so far.
* even
* odd
* format
+* lowercase
+* xor
== Extensibility
View
14 lib/constraints.rb
@@ -127,6 +127,20 @@ def unique(table, column, options)
end
##
+ # Allow only one of the values in the given columns to be true.
+ # Only reasonable with more than one column.
+ # See Enterprise Rails, Chapter 10 for details.
+ #
+ # Example:
+ # constrain :books, [], :xor => true
+ #
+ def xor(table, column, options)
+ addition = Array(column).map {|c| %{("#{c}" is not null)::integer} }.join(' + ')
+
+ "check (#{addition} = 1)"
+ end
+
+ ##
# Allow only text/strings of the exact length specified, no more, no less.
#
# Example:
View
24 test/sexy_pg_constraints_test.rb
@@ -872,4 +872,28 @@ def test_lowercase
end
end
+
+ def test_xor
+ ActiveRecord::Migration.constrain :books, [:xor_col_1, :xor_col_2], :xor => true
+
+ assert_prohibits Book, [:xor_col_1, :xor_col_2], :xor do |book|
+ book.xor_col_1 = 123
+ book.xor_col_2 = 321
+ end
+
+ assert_allows Book do |book|
+ book.xor_col_1 = 123
+ end
+
+ assert_allows Book do |book|
+ book.xor_col_2 = 123
+ end
+
+ ActiveRecord::Migration.deconstrain :books, [:xor_col_1, :xor_col_2], :xor
+
+ assert_allows Book do |book|
+ book.xor_col_1 = 123
+ book.xor_col_2 = 123
+ end
+ end
end
View
6 test/support/models.rb
@@ -9,9 +9,11 @@ def self.up
t.integer :from
t.string :isbn
t.string :as
+ t.integer :xor_col_1
+ t.integer :xor_col_2
end
end
-
+
def self.down
drop_table :books
end
@@ -24,7 +26,7 @@ def self.up
t.string :bio
end
end
-
+
def self.down
drop_table :authors
end
Please sign in to comment.
Something went wrong with that request. Please try again.