Prev | Current Page 189 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"


As you saw in our has_and_belongs_to_many example, Active Record glosses over the existence
of a join table, generally, because from a code point of view, it??™s not important to know it??™s there.
The join model, on the other hand, is like a join table, in that it has two foreign keys, but because
there is a model attached, it allows the intermediate table to have attributes that can more fully
describe the relationship than a simple join table.
Let??™s define our new table and refactor our models so we can use this type of association:
class Reseller < ActiveRecord::Base
has_many :distributions
has_many :farmers, :through => :distributions
end
class Distributions < ActiveRecord::Base
CHAPTER 4 ?–  CORE FEATURES OF ACTIVE RECORD 75
belongs_to :reseller
belongs_to :farmer
end
class Farmer < ActiveRecord::Base
has_many :distributions
has_many :resellers, :through => :distributions
end
Going back to our example, let??™s use this type of association. Here??™s our question: at what
price does a given farmer sell milk to a given reseller?
We know which farmer and which reseller we want information about; we just need to get
the price of milk to which these two have agreed.


Pages:
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201