开发者

Rails: Many-to-many Polymorphic Associations: Getting specific Type of Records

开发者 https://www.devze.com 2023-01-31 03:49 出处:网络
I have the following classes: class Region < ActiveRecord::Base has_many :geographical_relations, :as => :contained

I have the following classes:

 class Region < ActiveRecord::Base
   has_many :geographical_relations, :as => :contained
   has_many :geographical_units, :as => :container, :class_name => "GeographicalRelation"
 end

 class GeographicalRelation < ActiveRecord::Base
   belongs_to :container, :polymorphic => true
   belongs_to :contained, :polymorphic => true
 end

class Country < ActiveRecord::Base
  has_many :geographical_relations, :as => :contained
end

And I want to be able to, from a Country record, get all the Regions in which it is contained:

c = Country.find(1)
c.regions #=> should return all the regions in which c is cont开发者_高级运维ained

For now I've created the following method:

def regions
  self.geographical_relations.where(:container_type => "Region").map{|relation| relation.container}
end

But I wonder if there's any way to set an "has_many" association to do this for me.

Cheers.

EDIT:

after trying the alternatives suggested in the comments I only got nice ActiveRecord errors.

The has_many_polymorphs gem seems to be a good way to do this, but for Rails 3 it is not 'officially' supported so for my case it is not a good option.

So I will work with methods like the one described above, putting them in modules and including the respective modules inside each "container"/"contained" models. This seems to work ok. =) Only change I made, to avoid N+1 Queries was adding 'includes':

def regions
  self.geographical_relations.includes(:container).where(:container_type => "Region").map{|relation| relation.container}
end

Hopefully this works nicely and fast... =P =)

Anyway if anyone has an answer to solve this I'll look forward to see it! =)

Thanks all!

0

精彩评论

暂无评论...
验证码 换一张
取 消