这样做:
#app/models/car.rb
Class Car < ActiveRecord::Base
#fields id | manufacturer_id | name | model | other | information | created_at | updated_at
belongs_to :manufacturer
end
#app/models/manufacturer.rb
Class Manufacturer < ActiveRecord::Base
#fields id | name | foundation_year | etc | etc
has_many :cars
end
#app/models/model.rb
Class Model < Car
self.inheritance_column = :model # http://apidock.com/rails/ActiveRecord/ModelSchema/ClassMethods/inheritance_column
#this uses the Car model to populate different "models". It will allow you to identify the model based on the car - using the same table for all
end
您可能不需要为Model 提供单独的表,因为我认为Car 本身就是Model?相反,我会考虑使用STI (Single Table Inheritance) 根据您定义的模型调用任何特定的汽车模型:
#app/controllers/models_controller.rb
Class ModelsController < ApplicationController
def show
@cars = Model.find params[:id]
end
end
您应该真正使用具有多种型号的 STI(即,您的汽车中的每个 Model 都有一个特定的型号)。我建议反对它的原因是因为我假设您的每个 Car 对象都有自己的模型
如果不是这种情况,请使用以下建议。不过,
多个模型
处理模型/汽车的更简单方法是使用模型的简单关联:
#app/models/car.rb
Class Car < ActiveRecord::Base
# fields id | manufacturer_id | name | other | car | details | created_at | updated_at
has_many :models
belongs_to :manufacturer
end
#app/models/manufacturer.rb
Class Manufacturer < ActiveRecord::Base
has_many :cars
#fields id | name | foundation_year | other | attributes | created_at | updated_at
end
#app/models/model.rb
Class Model < ActiveRecord::Base
#fields id | name | wheels | engine | etc | created_at | updated_at
belongs_to :car
end
这使您能够为每个“汽车”创建不同的模型 - IE 有一个“运动”版本等。
活动记录
你会是最好的reading up on ActiveRecord associations,以及他们在 Rails 中扮演的角色
您必须考虑 Rails 以 对象 为中心 - 这意味着您所做的一切都必须尽可能地模块化。如果你有一个表对同一个对象有多个属性,你会遇到问题
您需要考虑对象之间的关系(关联),以达到构建模型以反映如何调用它们的程度。这一点非常重要,因为目前,您正在寻找数据库设置——您需要将焦点切换到 object 设置
理想情况下,你想要这样:
@car = Car.find params[:id]
@car.models.each do |model|
model.name
end