简体   繁体   English

Ruby on Rails:多态多态关联

[英]Ruby on Rails: Multiple polymorphic association

Is it possible to have a multiple polymorphic association? 是否有可能具有多重多态关联? I explain better: 我解释得更好:

  1. I have different kind of users: simple_user, society, collaborator, admin, and they are different in db fields and authorization through application. 我有不同类型的用户:simple_user,social,collaborator,admin,它们在db字段和应用程序授权方面有所不同。
  2. Every users can request for something 每个用户都可以申请
  3. A request can be for different services : traduction, consultance etc 请求可以是针对不同的服务 :traduction,consultance等

I was thinking about one table for each service: Traduction, consultance in which: 我正考虑为每项服务提供一张桌子:Traduction,咨询,其中:

has_one :request, :as => requestable

then just one table Request in which: 然后只有一个表请求,其中:

belongs_to :requestable, :polymorphic => true

but then is it possible to add another polymorphic association towards user tables ? 但是,是否可以向用户表添加另一个多态关联? How can I handle this relationship better? 我怎样才能更好地处理这种关系? Thanks for any advice 谢谢你的建议

Yes you can define multiple polymorphic associations. 是的,您可以定义多个多态关联。 They'll all use their own database columns. 他们都会使用自己的数据库列。

Create two columns user_type and user_id in your requests table and define this association : requests表中创建两列user_typeuser_id并定义此关联:

belongs_to :user, :polymorphic => true

Then you should be able to assign a Collaborator to a Request : 然后,您应该能够将Collaborator分配给Request

Request.create!(:user => Collaborator.first)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM