Two ideas:

1. Create two unique database indices, one each for each pairing order
and catch the exception on save on create.

2. Do it manually.

errors.add(:base, 'already exists') if
 (Klass.where(:sender_id => sender.id, :receiver_id => receiver.id) +
 Klass.where(:sender_id => receiver.id, :receiver_id =>
sender.id)).any?



On Mar 10, 2:09 pm, Danimal <[email protected]> wrote:
> Hello!
>
> I'm trying to figure out how to make two columns unique regardless of
> order. If order mattered, I could scope the validates_uniqueness_of,
> like 
> this:http://stackoverflow.com/questions/1633297/how-do-i-validate-two-fiel...
>
> But that's only one way. What if I have two columns, called "sender"
> and "receiver" and it doesn't really matter who is the sender and who
> is the receiver as long as that "grouping" doesn't exist previously.
>
> For example, assume I have this already in the database:
> Sender = 1, Receiver = 2
>
> Then, the following should occur:
> Sender = 1, Receiver = 3 # => PASS
> Sender = 1, Receiver = 2 # => FAIL
> Sender = 2, Receiver = 1 # => FAIL
> Sender = 3, Receiver = 1 # => FAIL (if the first one that passed
> already happened)
>
> I tried this:
>
> validates_uniqueness_of :sender_id, :scope => :receiver_id
> validates_uniqueness_of :receiver_id, :scope => :sender_id
>
> But that doesn't quite do it because they aren't tied together. I can
> custom-validate this but I was wondering if this pattern has already
> been accounted for somehow.
>
> Any pointers/references?
>
> Thanks!
>
> -Danimal

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to