【发布时间】:2010-12-28 23:31:18
【问题描述】:
我希望创建一个包含三个模型的 Rails 应用程序。一个模型代表汽车,另一个代表汽车可以涂漆的颜色,第三个代表某种颜色的汽车订单。构建这些模型之间关系的最佳方式是什么?
【问题讨论】:
标签: ruby-on-rails model-view-controller model
我希望创建一个包含三个模型的 Rails 应用程序。一个模型代表汽车,另一个代表汽车可以涂漆的颜色,第三个代表某种颜色的汽车订单。构建这些模型之间关系的最佳方式是什么?
【问题讨论】:
标签: ruby-on-rails model-view-controller model
我更喜欢 has_many :through 关系。这样,您就可以访问已订购某辆汽车的所有颜色,以及以某种颜色订购的所有汽车。
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
【讨论】:
我对此的想法与 Janteh 有点不同。当您下订单时,您会订购特定颜色的特定汽车,对吗?所以我认为汽车和颜色应该通过顺序关联起来,如下所示:
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
这主要是 Janteh 的建议,但我并没有直接将汽车与特定颜色联系起来。
【讨论】:
这是非常基本的东西。我建议你彻底阅读关于 Active Record 关联的Rails guide。为了让您继续前进:
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
【讨论】: