Dominic Bou-Samra
Dominic Bou-Samra

Reputation: 15416

Rails - enforcing a dichotomy using associations

I have a Devise User model with the standard fields. A User can have EITHER a Profile, or a House, but not both.

class User < ActiveRecord::Base

  attr_accessible ..... :profile_type
  has_one :profile, :dependent => :destroy
  has_one :house, :dependent => :destroy

end

In this current state, a User can have both a profile and a state. Suppose doing: User.first.profile returns the profile. I can then do User.first.house, returning nil. That doesn't seem very nice - in fact it seems like I'm going to run into invalid data issues later on.

Edit: This is for a situation where people are either looking for a place to stay, or they have a place to stay. So I have two categories of user that a person can be. These two categories are very distinct (i.e. a person looking for a place to stay will have very different fields to a person who has a place to stay).

Is there anyway to enforce this "either" relationship? I am very new to Rails mind you.

Upvotes: 0

Views: 43

Answers (1)

x1a4
x1a4

Reputation: 19485

You could handle this with a custom validation -

validate :has_either_profile_or_house_but_not_both

private

def has_either_profile_or_house_but_not_both
  if profile.present? && house.present?
    errors[:base] << "User can have either a profile or house, but not both."
  end
end

It's possible there's a cleaner way to do this via software design, but without knowing the problem you're solving, this is the best suggestion I have.

Upvotes: 1

Related Questions