Validating a self-referential association doesn't link back to the original instance in rails

I have a many-to-many model, following the example in this great railscast

My model links authors to each other. I'd like to validate that an author cannot friend himself. I know I can handle this at the UI level, but I'd love to have a validation in place to prevent a bug in the UI from allowing it. I've tried validates_exclusion_of, but it doesn't work. Here's my model for the relationship:

class Friendship < ActiveRecord::Base
  # prevent duplicates
  validates_uniqueness_of :friend_id, :scope => :author_id
  # prevent someone from following themselves (doesn't work)
  validates_exclusion_of :friend_id, :in => [:author_id]

  attr_accessible :author_id, :friend_id
  belongs_to :author
  belongs_to :friend, :class_name => "Author"
end

Answers


You'll have to use a custom validation:

class Friendship < ActiveRecord::Base
  # ...

  validate :disallow_self_referential_friendship

  def disallow_self_referential_friendship
    if friend_id == author_id
      errors.add(:friend_id, 'cannot refer back to the author')
    end
  end
end

Need Your Help

Own "Dynamic" Vector Class

c++ class dynamic vector

i am having trouble making my own dynamic vector class...