用户和服务是has many through
关系。但是,每个服务都有自己独特的属性。服务应该是单独的模型吗?或者我应该创建一个包含许多列的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 ...
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
或
One to Many
):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
答案 0 :(得分:0)
关于您的选项,Option A
是唯一合理的选项(DRY)。
如果有机会,永远不会复制代码,模型或视图。重用&重构 - 它使生活更简单。
如果您的服务 不同(您尚未说明它们是否存在),您可以从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
仅提取所需的属性。
我可能做的唯一事情就是将自定义属性添加到连接模型中。我仍然会为他们添加单独的字段,但我认为这样做会有点过分。