【问题标题】:Change many to many polymorphics association to one to many将多对多多态关联更改为一对多
【发布时间】:2016-04-06 01:42:09
【问题描述】:

用户和活动与职业有多对多关联。我想将与用户的职业关联更改为多对一。如何修改?

用户

has_many :common_occupations, :as => :profession
has_many :occupations, :through => :common_occupations

职业

class Occupation < ActiveRecord::Base
has_many :users, :through => :common_occupations, :source => :profession, :source_type => "User"
has_many :campaigns, :through => :common_occupations, :source => :profession, :source_type => "Campaign"
has_many :common_occupations

广告系列

has_many :common_occupations, :as => :profession
has_many :occupations, :through => :common_occupations

普通职业

belongs_to :occupation
belongs_to :profession, :polymorphic => true

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-3.2


    【解决方案1】:

    用户

    has_many :common_occupations, :as => :profession
    belongs_to :occupation
    

    职业

    has_many :users
    has_many :campaigns, :through => :common_occupations, :source => :profession, :source_type => "Campaign"
    has_many :common_occupations
    

    广告系列

    has_many :common_occupations, :as => :profession
    has_one :occupation, :through => :common_occupations
    

    普通职业

    belongs_to :occupation
    belongs_to :profession, :polymorphic => true
    

    此外,您必须将occupation_id 列添加到users 表中。

    此外,之后您可以删除职业多态关联,因为它将不再需要。

    【讨论】:

      【解决方案2】:

      最简单的方法是使用has_one 而不是has_many

      class User < AR::Base
        has_one :common_occupation, :as => :profession
        has_one :occupation, :through => :common_occupation
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多