Reputation: 631
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
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