0

I'm a brand new developer so this might be a dumb question.

I am trying to setup a webapp which will store stats on geographic data.

  • I have a model called Stat which has fields for basic statistical information (median, variance, avg, etc.).
  • I have setup models for each geographic units City, Zip, Sub-Zip

What I want to do know is associate the Stat model with Cities, Zips, and Sub-Zips; that is every stat model belongs to either a city, zip, or sub-zip while a geographic unit (city,zip,sub-zip) can have multiple stats.

How do I setup the associations and migration to do this? I've looked through the Rails guides but it doesn't seem to cover a relationship where an object can belong to different models (but only one of them). Or should I set up my models differently?

slykat
  • 856
  • 1
  • 11
  • 18

2 Answers2

1

You said:

every stat model belongs to either a city, zip, or sub-zip while a geographic unit (city,zip,sub-zip) can have multiple stats.

So I think you want to set up Polymorphic Associations:

With polymorphic associations, a model can belong to more than one other model, on a single association.

So your association maybe like this:

class Stat
  belongs_to :statsable, polymorphic: true
end

class City
  has_many :stats, as: :statsable
end

class Zip
  has_many :stats, as: :statsable
end

class Subzip
  has_many :stats, as: :statsable
end
Thanh
  • 8,219
  • 5
  • 33
  • 56
0

This can be done with rails association. Following link explain you this in details,

http://guides.rubyonrails.org/association_basics.html

maximus ツ
  • 7,949
  • 3
  • 25
  • 54
  • Hi, I've looked over that document and I'm not sure how to add the association. In City, Zip, and Sub-Zip models I believe I use **has_one** but I don't what to use in the **Stat** model. If a Stat only belongs to City I would use **belongs_to** but in this case it could belong to many models. – slykat Dec 05 '12 at 06:00
  • if stat and other models like city has many to many association, then you have to use has_and_belongs_to_many association. This can be done with join table. Look for this in same link. – maximus ツ Dec 05 '12 at 06:07