Ruby on rails 有多个STI,且属于多个STI,按类型限制为唯一

Ruby on rails 有多个STI,且属于多个STI,按类型限制为唯一,ruby-on-rails,sti,Ruby On Rails,Sti,我使用的STI模型有很多关系。 因此,我有User和许多不同类型的Template,比如maintplate

我使用的STI模型有很多关系。 因此,我有
User
和许多不同类型的
Template
,比如
maintplate
<代码>非模板;等
有没有办法限制每个用户对所有类型都只有一个
main模板
和一个
notsomantemplate
,依此类推?

既然您已经在使用STI,您可以尝试
拥有一个

class Template < ActiveRecord::Base
  has_many :users, through: template_choice
  ...
end

class MainTemplate < Template
  ...
end

class TemplateChoice < ActiveRecord::Base
  belongs_to :template_choice
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one  :main_template, through: :template_choice
  has_one  :not_so_main_template, through: :template_choice
  ...
end
类模板
既然您已经在使用STI,您可以尝试
有一个

class Template < ActiveRecord::Base
  has_many :users, through: template_choice
  ...
end

class MainTemplate < Template
  ...
end

class TemplateChoice < ActiveRecord::Base
  belongs_to :template_choice
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one  :main_template, through: :template_choice
  has_one  :not_so_main_template, through: :template_choice
  ...
end
类模板
既然您已经在使用STI,您可以尝试
有一个

class Template < ActiveRecord::Base
  has_many :users, through: template_choice
  ...
end

class MainTemplate < Template
  ...
end

class TemplateChoice < ActiveRecord::Base
  belongs_to :template_choice
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one  :main_template, through: :template_choice
  has_one  :not_so_main_template, through: :template_choice
  ...
end
类模板
既然您已经在使用STI,您可以尝试
有一个

class Template < ActiveRecord::Base
  has_many :users, through: template_choice
  ...
end

class MainTemplate < Template
  ...
end

class TemplateChoice < ActiveRecord::Base
  belongs_to :template_choice
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one  :main_template, through: :template_choice
  has_one  :not_so_main_template, through: :template_choice
  ...
end
类模板
让我重申我理解的问题陈述

您希望
User
每个模板最多有一种。i、 e

  • 1个主模板、1个非着色模板等
  • 不需要与
    模板(父表)建立直接关系
  • 每个模板可由多个用户使用
基于上述假设,我建议您采取以下措施:

  • 删除
    用户
    模板
  • 添加迁移以将
    main\u template\u id
    添加到
    User
  • 添加以下关联:

    class MainTemplate < Template
        has_many :users
    end
    
    class NotSoMainTemplate < Templete
        has_many :users
    end
    
    class class User < ActiveRecord::Base
        belongs_to :main_template
        belongs_to :not_so_main_template
    end
    
    class MainTemplate