Best way to model these relationships in Rails
I'm looking to create a Rails application with three 开发者_C百科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?
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
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.
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
精彩评论