Changing the default polymorphic type name

I am using Ruby on Rails 3 and I would like to change the default column type name used by polymorphic association.

For example, if I have this class:

class Comment < ActiveRecord::Base
  ...
end

and I implement a polymorphic association for this, I would like to use column names of type comm_idand comm_typeinstead of commentable_idand commentable_type. Is it possible? If so, what do I need to change for the Comment class?

+3
source share
3 answers

There is no way in the Rails API to override the default column name used for polymorphic associations.

See this answer for a possible solution.

+2
source

, :

# Comment
belongs_to :comm, :polymorphic => true

# Everything else
has_many :comments, :as => :comm
0

I did this in rails 6 in my old database. This should work for rails> = 4.2.1 ( see here )

# booking model
class Booking < ApplicationRecord
  has_many :user_notes, as: :notable, foreign_type: :note_type, foreign_key: :type_id
end
# booking model
# here polymorphic columns are 'note_type' and 'type_id'
class UserNote < ApplicationRecord
  belongs_to :notable, polymorphic: true, foreign_type: :note_type, foreign_key: :type_id
end
0
source

All Articles