2013-03-07 152 views
3

在我的新Rails項目中,我需要訪問我的舊數據庫。所以我創建了一些傳統模型。 我有照片和評論(commentable_id和commentable_type)has_many與多態關聯中的class_name

當我打電話

遺產:: Photo.last.comments

它不會因爲commentable_type工作之間的多態性ASSOCATION是'照片'而不是'LegcayPhoto'。

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 

我也有在傳統/ comments.rb問題。 有沒有辦法爲belongs_to添加命名空間:commentable,:polymorphic => true?

+0

在評論模型中,它應該是belongs_to:photo,:class_name => Legacy :: Photo – 2013-03-07 12:21:21

+0

但它不再是多態的。 – mm1 2013-03-07 12:28:55

回答

-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) 

它仍然會工作。