Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

ruby-on-rails - 如何将3个不同模型关联到2个模型关系中(How to associate 3 different models in to a 2 model relationship)

The gist of the matter is I want to know the best way to associate the below setup.

(问题的要点是我想知道关联以下设置的最佳方法。)

I have 2 customer models.

(我有2个客户模型。)

Individual Customer & Corporate Customer .

(Individual CustomerCorporate Customer 。)

I have another Vehicle model.

(我有另一个Vehicle模型。)

Which I would like to maintain separately.

(我想单独维护。)

I would like to have a HMT model called VehicleOwner .

(我想要一个名为VehicleOwner的HMT模型。)

Which now adds the r/ship of any of the two(2) customers as an owner & the vehicle.

(现在,将两(2)个客户中的任何一个的r / ship添加为所有者和车辆。)

The reason for this approach is an architecture design to allow the same vehicle to be migrated to other customers and not have every time a customer wants to add a vehicle;

(之所以采用这种方法,是因为其架构设计允许将同一辆车迁移到其他客户,而不是每次客户都想添加一辆车。)

they keep adding a vehicle even if we have it.

(即使我们有车辆,他们也会继续添加。)

My question is this?

(我的问题是这个吗?)

How can I link in the Vehicle Owner.

(如何链接车主。)

That the owner can either be an individual customer or a corporate customer.

(所有者可以是个人客户也可以是公司客户。)

Or is there another better way to map the two(2) customers with a vehicle.

(还是有另一种更好的方法来用车辆映射两个(2)客户。)

Thanks

(谢谢)

  ask by N. Maina translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perhaps you are looking for Polymorphic association in Rails, in your case it would be, VehicleOwner model should look like

(也许您正在寻找Rails中的多态关联 ,就您而言, VehicleOwner模型应该看起来像)

belongs_to :customer, polymorphic: true

In IndividualCustomer and CorporateCustomer models

(在IndividualCustomerCorporateCustomer模型中)

has_many :vehicle_owners, as: :customer

This is just an example of how to implement this, you can read more about in official Rails guides

(这只是如何实现此示例,您可以在Rails官方指南中了解更多信息)

https://guides.rubyonrails.org/association_basics.html#polymorphic-associations

(https://guides.rubyonrails.org/association_basics.html#polymorphic-associations)

Hope that helps!

(希望有帮助!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...