Rails 3 model with belongs_to different tables exclusively in each record
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 AlphaIt开发者_JAVA技巧ems and BetaItems instead?
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
精彩评论