0

Possible Duplicate:
HABTM Polymorphic Relationship

Currently I'm implementing a many to many relationship by defining the model of the relationship, and then setting an has_many relationship :through the relationship model. something like this:

class WorldCup < ActiveRecord::Base
  has_many :country_taggings#, :as => :entity
  has_many :countries, :through => :country_taggings
end

class Country < ActiveRecord::Base
  has_many :country_taggings
end

class CountryTaggings < ActiveRecord::Base
   belongs_to :country
   belongs_to :world_cup
   # belongs_to :entity, :polymorphic => true
end

this would be, of course, easily translatable into an has_and_belongs_to_many, if it were not for the stuff I commented out there. So, the relationship from the parent to the relationship model is polymorphic. The verbosity of actually defining the in-between relationship model is killing me. Isn't there a way to reccur to has_and_belongs_to_many and somehow figure out a way to polymorf it?

Community
  • 1
  • 1
ChuckE
  • 5,610
  • 4
  • 31
  • 59

2 Answers2

0

try this -

http://ruby-on-rails-dipak-panchal.blogspot.in/2012/10/has-many-through-relationship.html

class WorldCup < ActiveRecord::Base
  has_many :country_taggings
  has_many :countries, :through => :country_taggings
end

class Country < ActiveRecord::Base
  has_many :country_taggings
  has_many :worldcups, :through => :country_taggings
end

class CountryTaggings < ActiveRecord::Base
  belongs_to :country
  belongs_to :world_cup
end

and also see this

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

Dipak Panchal
  • 5,996
  • 4
  • 32
  • 68
0
class WorldCup < ActiveRecord::Base

  has_many :country_taggings

 has_many :countries, :through => :country_taggings

end

class Country &lt; ActiveRecord::Base
  has_many :country_taggings
end

class CountryTaggings < ActiveRecord::Base
  belongs_to :entity, :polymorphic => true

 belongs_to :country

 belongs_to :world_cup

end
Valentin Rocher
  • 11,667
  • 45
  • 59
vijikumar
  • 1,805
  • 12
  • 16