# Can I have a constraint like this.....?

**URL:** <https://www.ruby-forum.com/t/can-i-have-a-constraint-like-this/145433>\
**Category:** Rails\
**Created:** [August 9, 2008, 10:37am UTC](https://www.ruby-forum.com/t/can-i-have-a-constraint-like-this/145433 "2008-08-09T10:37:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![greg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/71c47a/32.png) [@greg](https://www.ruby-forum.com/u/greg)\
**Post date:** [August 9, 2008, 10:37am UTC](https://www.ruby-forum.com/t/can-i-have-a-constraint-like-this/145433/1 "2008-08-09T10:37:26Z")

</div>

Hi,

Is it possible to have a SQL constraint (I am on mysql at the moment)  
for  
the following?

Background: Table has a parent\_id column that allow a row in the table  
to  
reference another row in the table. The table list bank transactions,  
but  
allow the ability to say row A is actually made up of two separate items  
(which you enter manually) in row B & C. For example:

Row 1 - $100 (bank transaction)  
Row 2 - $20 (item X), parent\_id=1  
Row 3 - $80 (item Y), parent\_id=1

Q - Can I create a constraint that requires, for a successful save, that  
SUM(parent) = SUM(children).

That is this would make sure the table data is always consistent. It  
would  
not be possible to allocate Row 2 as child and forget to add Row 3 as  
remaining child, as they wouldn’t add up.

Is this possible? Or is there a way to protect against this somehow? Is  
there anything in Rails that could help at the application layer if  
mysql  
can’t implement such a constraint?

Thanks

---

<div class="post-metadata">

**Author:** ![greg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/71c47a/32.png) [@greg](https://www.ruby-forum.com/u/greg)\
**Post date:** [August 10, 2008, 12:42pm UTC](https://www.ruby-forum.com/t/can-i-have-a-constraint-like-this/145433/2 "2008-08-10T12:42:38Z")

</div>

Greg H. wrote:

> Is this possible? Or is there a way to protect against this somehow? Is  
> there anything in Rails that could help at the application layer if  
> mysql  
> can’t implement such a constraint?
> 
> Thanks

I’m not sure about MySQL, but you could probably do something with a  
custom validation in Rails. Google for

Rails “custom validations”

and you should find plenty to get you going.

Peace,  
Phillip
