Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

Change many to many polymorphics association to one to many

User and campaign has many to many association with occupation.I want to change occupation association with user many to one. How I modify it?

User

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

Occupation

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

Campaign

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

CommonOccupation

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

Upvotes: 0

Views: 41

Answers (2)

PinnyM
PinnyM

Reputation: 35533

The simplest approach would be to use has_one instead of has_many:

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

Upvotes: 1

Świstak35
Świstak35

Reputation: 350

User

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

Occupation

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

Campaign

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

CommonOccupation

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

Moreover you would have to add occupation_id column to users table.

Also, after that you could remove profession polymorphic association as it will be no longer needed.

Upvotes: 1

Related Questions