sscirrus
sscirrus

Reputation: 56749

Repairing a polymorphic association

I'm fixing a polymorphic association that was 'kind of' set up in the past. Here are the details.

User.rb has fields:
user_type_id
user_type

I need User to belong to Company or Employee.

The problem I'm having is because the User.rb fields are not named using Rails convention (something like usable_type and usable_id). How can I set up the association given the fields I have?

Upvotes: 0

Views: 155

Answers (2)

Michael Fairley
Michael Fairley

Reputation: 13218

There's an undocumented :foreign_type option on belongs_to:

class User < ActiveRecord::Base
  belongs_to :user_type, :polymorphic => true, :foreign_type => 'user_type'
end

Upvotes: 2

Andrea
Andrea

Reputation: 420

It is easiest to change the names of the fields to suit the Rails convention: since the polymorphic association is not properly set up yet, and those fields should not be used for anything else, so you should not have a problem.

Essentially you need to choose a name xyz to suit the following

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

class Employee < ActiveRecord::Base
    has_many :users, :as => :xyz
end

class Company < ActiveRecord::Base
    has_many :users, :as => :xyz
end

where your user model has fields

User
xyz_id    :integer
xyz_type    :string

This will also make for more maintainable code later on.

Upvotes: 0

Related Questions