alecvn
alecvn

Reputation: 631

How do I map an association through a model's parents if it can only belong to one of them?

Let's say I have active records Measurable, Bag and ShoppingBag(which is basically a specific type of bag):

class Measurable < ActiveRecord::Base

    belongs_to :bag, class_name: Bag
    belongs_to :shopping_bag, class_name: ShoppingBag

end

class Bag  < ActiveRecord::Base

    has_one :shopping_bag, class_name: ShoppingBag

end

class ShoppingBag < ActiveRecord::Base

    belongs_to :bag, class_name: Bag

end

The Measurable can only belong to either a Bag or a ShoppingBag.

How can I setup the Measurable so that when I call

measurable.bag

it will get to the Bag it is associated with either directly, or via its ShoppingBag, without changing the relationship of the bags.

Upvotes: 0

Views: 263

Answers (1)

Jaffa
Jaffa

Reputation: 12719

If your shopping bag is a specific bag, then you can declare it as a subclass.

class ShoppingBag < Bag
  // specific attributes
end

If you can't do that (as you suggest in your comment), then you can override the bag method of you measurable :

def bag
  super || shopping_bag.bag
end

Then you can add a mutual exclusion validation (not tested)

validates :bag, absence: true, if: :shopping_bag
validates :shopping_bag, absence: true, if: :bag

Upvotes: 1

Related Questions