What is the most elegant way to validate the presence of ONLY one out of two attributes using Rails?

Posted by marcgg on Stack Overflow See other posts from Stack Overflow or by marcgg
Published on 2010-03-24T13:29:47Z Indexed on 2010/03/24 13:33 UTC
Read the original article Hit count: 307

class Followup < ActiveRecord::Base
  belongs_to :post
  belongs_to :comment
end

This model needs to only have either a post or a comment, but only one of the two.

Here's the rspec for what I'm trying to do:

  it "should be impossible to have both a comment and a post" do
    followup = Followup.make
    followup.comment = Comment.make
    followup.should be_valid
    followup.post = Post.make
    followup.should_not be_valid
  end

I can see a bunch of ways of doing this, but what would be the most elegant way of doing this?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails