3

新しいRailsプロジェクトでは、古いデータベースにアクセスする必要があります。そこで、いくつかのレガシーモデルを作成しました。写真とコメントの間にポリモーフィックな関連付けがあります(commentable_idとcommentable_type)

電話すると

Legacy :: Photo.last.comments

commentable_typeは「LegcayPhoto」ではなく「Photo」であるため、機能しません。

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

レガシー/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

レガシー/comment.rb

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

また、legacy/comments.rbにも問題があります。:commentable、:polymorphic => trueのbelongs_toの名前空間を追加する方法はありますか?

4

1 に答える 1

-1

おそらく最も理想的なアプローチではありませんが、has_many関連付けを構築する代わりに、 が返すものを模倣する ActiveRecord クエリを返すメソッドを簡単に定義できるようになりましたhas_many

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

今でも、次のようなことを言うことができます。

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

そしてそれはまだ動作します。

于 2014-08-15T11:36:10.833 に答える