mm1
mm1

Reputation: 364

has_many with class_name in polymorphic associations

In my new Rails Project I need access to my old database. So I created some legacy Models. I have a polymorphic assocation between photos and comments(commentable_id and commentable_type)

When I call

Legacy::Photo.last.comments

it doesn't work because the commentable_type is 'Photo' and not 'LegcayPhoto'.

SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = $1 AND "comments"."commentable_type" = $2  [["commentable_id", 123], ["commentable_type", "Legacy::Photo"]]

legacy/photo.rb

module Legacy
  class Photo < ActiveRecord::Base
    establish_connection "legacy_#{Rails.env}"
    belongs_to :user, :class_name => 'Legacy::User' #works fine
    has_many :comments, :class_name => 'Legacy::Comment', :as => :commentable
  end
end

legacy/comment.rb

module Legacy
  class Comment < ActiveRecord::Base
    establish_connection "legacy_#{Rails.env}"
    #?? belongs_to :commentable,  :polymorphic => true
  end
end

I also have a problem in legacy/comments.rb. Is there a way to add the namespace for belongs_to :commentable, :polymorphic => true ?

Upvotes: 3

Views: 1339

Answers (1)

Topher Fangio
Topher Fangio

Reputation: 20687

Perhaps not the most ideal approach, but instead of building the has_many association, you can now easily define a method that returns an ActiveRecord query which imitates what the has_many returns:

module Legacy
  class Photo < ActiveRecord::Base
    establish_connection "legacy_#{Rails.env}"
    belongs_to :user, :class_name => 'Legacy::User' #works fine

    def comments
      Comment.where("commentable_type='LegacyPhoto' AND commentable_id=?", self.id)
    end
  end
end

Now, you can still say things like:

Legacy::Photo.comments.where(created_at > 1.day.ago)

and it will still work.

Upvotes: -1

Related Questions