3

I have some models like these:

class Alpha < ActiveRecord::Base
 has_many :items 
end    

class Beta < ActiveRecord::Base
 has_many :items
end

class Item < ActiveRecord::Base
 belongs_to :alpha
 belongs_to :beta
end

But i want Item model in each database record to belong either to an :alpha or to a :beta but NOT both. Any nice way to do it in Rails 3? or should I model it with AlphaItems and BetaItems instead?

dotoree
  • 2,983
  • 1
  • 24
  • 29

1 Answers1

9

You probably want to use a Polymorphic Association for this. More details - http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

class Alpha < ActiveRecord::Base
  has_many :items, :as => :itemable
end    

class Beta < ActiveRecord::Base
  has_many :items, :as => :itemable
end

class Item < ActiveRecord::Base
  belongs_to :itemable, :polymorphic => true
end
Dogbert
  • 212,659
  • 41
  • 396
  • 397