Has_many :through with a polymorphic join


#1

Hi,
Four tables: users, user_counties, uk_counties and us_counties.

Each user has many counties, and each county has many users, so I
decided to make user_counties a polymorph, so it can have counties
from different countries (each country requires a completely different
set of tables with a completely different set of properties, that’s
why there’s one table for uk_counties and one for us_counties, with
more to follow when more countries are supported). This would require:

class User…
has_many :counties, :through => user_counties #counties is the
imaginary table
end

class UserCounties
belongs_to :counties, :polymorphic => true
end

Is this possible? If not, can anyone think of a way around it other
than adding another table into the chain? And (bonus question… not
required, just for fun) what would the reverse relationship look like
(ie, how would uk_counties relate to users)?
-Nathan


#2

unknown wrote:

Four tables: users, user_counties, uk_counties and us_counties.

Each user has many counties, and each county has many users, so I
decided to make user_counties a polymorph…

http://blog.hasmanythrough.com/articles/2006/04/03/polymorphic-through


Josh S.
http://blog.hasmanythrough.com


#3

Ah, thanks Josh. Nice to see that you’d already written an in-depth
answer to my problem.
-N


#4

unknown wrote:

Ah, thanks Josh. Nice to see that you’d already written an in-depth
answer to my problem.

About half the reason I keep the blog is to avoid having to repeat
myself :slight_smile:
Glad you found it useful!


Josh S.
http://blog.hasmanythrough.com