1

I created a scaffold in ror in order to contain some relations between elements

+----------------------+
| left | right | score |
+----------------------+

So, if I have an entry a, b, 10, it means the relation from a to b is 10. But as left and right, represents fk's of the same kind of entity, we can conclude that the relation from b to a is also 10.

Doing something like validates_uniqueness_of :left, :scope => [:right] will not prevent the pair from appearing reverted in the table like so : b, a, 10

I suppose something like :

validates_uniqueness_of :left, :scope => [:right]
validates_uniqueness_of :right, :scope => [:left]

could do the trick, but is there a cleaner or more appropriate way to validate the uniqueness of pairs symmetrically ?

Once this is answered, the job is almost done.

How do I prevent the same value of appearing on both columns ?

eg. Such an entry should not be allowed : a, a, 15

Thanks for your consideration.

CrumbleZ
  • 109
  • 6
  • Possible duplicate of [How do you validate uniqueness of a pair of ids in Ruby on Rails?](http://stackoverflow.com/questions/923796/how-do-you-validate-uniqueness-of-a-pair-of-ids-in-ruby-on-rails) – infused Mar 07 '16 at 17:25
  • @infused I don't see what's in the dup target which isn't already in the question. Also, it doesn't handle left and right being swapped. – Andrew Grimm Mar 08 '16 at 02:17

1 Answers1

0

There might be a validation specific to your needs. I don't know.

If not, consider using a custom validation

class MyValidator < ActiveModel::Validator
  def validate(record)
    unless record.name.starts_with? 'X'
      record.errors[:name] << 'Need a name starting with X please!'
    end
  end
end

class Person
  include ActiveModel::Validations
  validates_with MyValidator
end
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338