0

可能重复:
HABTM 多态关系

目前我正在通过定义关系模型来实现多对多关系,然后设置一个 has_many 关系:通过关系模型。像这样的东西:

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

当然,如果不是因为我在那里评论的东西,这将很容易翻译成 has_and_belongs_to_many。因此,从父级到关系模型的关系是多态的。实际定义中间关系模型的冗长让我感到厌烦。有没有办法重现 has_and_belongs_to_many 并以某种方式找到一种方法来多态化它?

4

2 回答 2

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
于 2012-10-12T11:06:43.733 回答
0

尝试这个 -

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

也看到这个

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

于 2012-10-12T07:50:00.903 回答