I'm looking to create a Rails application with three models. One model represents cars, another represents the colors cars can be painted, and a third represents an order for a car in some color. What's the best way to structure the relationship between these models?
+3
A:
This is pretty basic stuff. I suggest you read the Rails guide about Active Record associations thoroughly. To get you going:
class Car < ActiveRecord::Base
has_many :orders
belongs_to :color
end
class Color < ActiveRecord::Base
has_many :cars
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :car
belongs_to :color
end
Janteh
2009-12-22 03:57:34
Not a bad start, may want to add a validation to Order to ensure that the Color in an Order is compatible with the selected Car.
EmFi
2009-12-22 04:01:40
A:
I thought about this a bit differently than Janteh. When you place an order, you order a particular car in a particular color, right? So I think cars and colors should be associated through the order, something like this:
class Car < ActiveRecord::Base
has_many :orders
end
class Color < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :car
belongs_to :color
end
This is mostly what Janteh suggested, but I didn't associate a car directly with a particular color.
mipadi
2009-12-22 04:07:43
But you also want to know in what colors you can order a certain car, right?
Janteh
2009-12-22 05:18:00
A:
I'd prefer a has_many :through relationship. That way you can access all of the colors a certain car car has been ordered in, and all of the cars ordered in a certain color.
class Car < ActiveRecord::Base
has_many :orders
has_many :colors, :through => :orders
end
class Color < ActiveRecord::Base
has_many :orders
has_many :cars, :through => :orders
end
class Order < ActiveRecord::Base
belongs_to :car
belongs_to :color
end
Seth Archer
2009-12-22 07:11:49