views:

68

answers:

3

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
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
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
But you also want to know in what colors you can order a certain car, right?
Janteh
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