简体   繁体   English

Rails:复杂的多态关联

[英]Rails: Complex polymorphic association

I have a User model who has one Profession (Designer, Model, Photograph, ...). 我有一个用户模型,有一个专业(设计师,模型,照片,......)。 Each profession has specific attributes, so each profession has its own table. 每个职业都有特定的属性,因此每个职业都有自己的表。

Now in my User I would like to say that a User has_one :profession, where the profession is Photograph, Designer, or whatever else. 现在在我的用户中我想说一个用户has_one:专业,专业是照片,设计师或其他任何东西。

My first idea was to use the Profession model as a STI but if I do this I cannot have a table for each real profession... 我的第一个想法是将职业模型用作STI,但如果我这样做,我就无法为每个真正的职业提供表格......

How would you design this? 你会怎么设计这个?

Thanks, Greg 谢谢,格雷格

I would flip the has_one association to a belongs_to and use polymorphic associations. 我会将has_one关联翻转为belongs_to并使用多态关联。 The model code would be: 型号代码为:

class User < ActiveRecord::Base
  belongs_to :profession, :polymorphic => true
end


# similar code for other professions
class Designer < ActiveRecord::Base
  has_one :user, :as => :profession
end

Migration would look like this: 迁移看起来像这样:

change_table :users do |t|
  t.references :profession, :polymorphic => true
end

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

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