Rails 3 model with individual table ownership in each entry exclusively

I have several such models:

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 the model of the element in each database entry to belong to either the alpha or beta, but not both. Any good way to do this in Rails 3? or should I simulate it using AlphaItems and BetaItems?

+3
source share
1 answer

You probably want to use the 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
+8
source

All Articles