Change the default polymorphic type-column name
I am using Ruby on Rails 3 and I would like to change the default type-column name used by a polymorphic association.
For example, if I have this class:
class Comment < ActiveRecord::Base
...
end
and I implement for that a polymorphic association, I wou开发者_开发技巧ld like to use the type-column names comm_id
and comm_type
instead of commentable_id
and commentable_type
. Is it possible? If so, what I have to change for the Comment class?
There's no way in Rails API to override the default column name used for polymorphic associations.
Take a look at this answer for a possible solution.
I did this in rails 6 on my legacy database using the foreign_type:
option. 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
In your case, why not just change the association to:
# Comment
belongs_to :comm, :polymorphic => true
# Everything else
has_many :comments, :as => :comm
精彩评论