用户和服务是有很多通过
的关系。但是,每项服务都有其独特的属性。服务应该是单独的模型吗?或者我应该创建一个包含许多列(针对每个属性)的 service
模型。性能是一个问题。
3 个示例服务:
Service 1 requires zipcode:string, phone_number:string
Service 2 requires licensePlate:string, carColor:string
Service 3 requires shoeSize:integer, shoeColor: string
...
Service 100 ...
选项 A(has_many :through
):
rails g model services name:string
Join Model:
rails g model service_user zipcode:string phone_number:string licensePlate:string carColor:string shoeSize:integer shoeColor: string
或
选项 B(单独的一对多
):
rails g model service1 user_id: integer zipcode:string phone_number:string
rails g model service2 user_id: integer licensePlate:string carColor:string
rails g model service3 user_id: integer shoeSize:integer shoeColor: string
最佳答案
关于您的选择,选项 A
是唯一可能的 ( DRY )。
如果有机会,绝不复制代码、模型或 View 。重用和重构 - 让生活更简单。
如果您的服务那样不同(您没有说明它们是否不同),您将受益于寻找 STI (Single Table Inheritance) ;这将在数据库中保存一组数据,使您可以调用多个模型。虽然欢迎您尝试,但我不会向您推荐此方法。
--
我个人会使用以下内容:
#app/models/service.rb
class Service < ActiveRecord::Base
# id service_type zipcode phone_number license_plate car_color shoe_color
enum service_type: [:1, :2, :3]
has_many :user_services
has_many :users, through: :user_services
end
#app/models/user_service.rb
class UserService < ActiveRecord::Base
belongs_to :user
belongs_to :service
end
#app/models/user.rb
class User < ActiveRecord::Base
has_many :user_services
has_many :services, through: :user_services
end
我会将您提到的所有属性都包含在一个模型中。老实说,没有那么多。性能下降只有在您开始查看大量 NULL 数据后才会真正发生。您可以随时使用 select
仅提取您需要的属性。
我可能做的唯一一件事就是将自定义属性添加到连接模型。我仍然会为它们添加单独的字段,尽管我认为这样做有点过分了。
关于ruby-on-rails - 如何构建具有多列的 HMT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34887011/