Reputation: 48626
I'm having some trouble arranging my models in an efficient way. Thing of these models :
City
Building
CityBuilding
WoodProduction
Now, of course, a city has many buildings through city_buildings. A city building has some basic attributes like the population living there. However, there are 2 buildings that need to hold more information, like the amount of wood produced, if we are talking about a sawmill.
So, in this example, the sawmill, i would want to be able to do something like :
current_city.wood_production.amount
And get the amount of wood, provided that a city has one wood_production association. Everything fine till this point.
But, wood_production also needs to store a rate at which the wood is produced. This rate is produced by a formula, that needs information about the level of the sawmill building (found in city_buildings).
I have made it work by using a nested association in wood_production like :
has_many :city_buildings, :through => :city
So, now i can execute something like :
c = City.first
w = c.wood_production
w.city_buildings.where(:building_id => ...).level
Which although it works, if feels very unnatural and i'm kinda convinced that there is a much better way of achieving this.
Anything to suggest please :) ?
EDIT : I feel that scope may be a part of a nice solution, like specifying a scope for the sawmill building, maybe someone has thought of something in more detail, i'm kinda processing that idea now.
Upvotes: 1
Views: 52
Reputation: 3283
right so you have the through association correct. If the building_id
of the sawmill is fixed then you can add another association
has_many :sawmills, :through => :city, :source => :city_buildings, :conditions => {:building_id => SAWMILL_BUILDING_ID}
w.sawmills.first.level
edit: has_one :through to a has_many would not work
Upvotes: 1