将多对多变量关联更改为一对多

时间:2016-01-01 15:20:36

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

用户和活动与职业有很多关联。我想与用户多对一地改变职业关联。我如何修改它?

用户

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

CommonOccupation

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

2 个答案:

答案 0 :(得分:1)

用户

Id1, value1
Id1, value2
Id2, value1
Id2, value2
Id2, value3
Id3, value1
Id3, value2
Id3, value3
Id3, value4
Id3, value5 

职业

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

CommonOccupation

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

此外,您必须将belongs_to :occupation belongs_to :profession, :polymorphic => true 列添加到occupation_id表格。

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

答案 1 :(得分:1)

最简单的方法是使用has_one代替has_many

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