What is the most elegant way to validate the presence of ONLY one out of two attributes using Rails?
- by marcgg
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?