activerecord - Rails 3 polymorphic association with foreign_type column as integer -
we have problem polymorphic relation in rails/activerecord. mentioned in other question . reason need kind of polymorphic relation integer foreign_type column number of records in table, have 40 million record in table number raising. try save storage @ database server memory consumption concerning index handling @ database.
the question mentioned earlier related rails 2 , if tried uses rails 3 doesn't work. method of module never called , can't see why.
i have mapping column types see in migration class
class notification < activerecord::base belongs_to :notifiable, :polymorphic => true end
class user < activerecord::base attr_accessible :name has_many :notifications, :as => :notifiable end
class comment < activerecord::base attr_accessible :text has_many :notifications, :as => :notifiable end
class message < activerecord::base attr_accessible :title, :text has_many :notifications, :as => :notifiable end
class activity < activerecord::base attr_accessible :title, :description has_many :notifications, :as => :notifiable end
class createnotification < activerecord::migration def change create_table :notifications |t| t.integer :notifiable_id t.integer :notifiable_type # should tinyint @ database t.timestamps end end end
i map comment , user numeric value , save numeric value instead of class name type information.
to make polymorphic belongs_to working, can that:
in config/initializers
directory, create file , put theses lines:
module activerecord # = active record belongs polymorphic association module associations class belongstopolymorphicassociation < belongstoassociation #:nodoc: def klass type = owner.send(reflection.foreign_type) type.presence && type.constantize end end end end
then in each model, override notifiable_type
(define hash constant , put anywhere like):
def notifiable_type { 0: 'user', 1: 'comment', 3: 'message' }[read_attribute(:notifiable_type)] end
and has_many
, try (set int_class_type each model):
has_many :notifications, :conditions => ["`notifiable_type` = ?", int_class_type], :foreign_key => 'notifiable_id'
Comments
Post a Comment