在我的新 Rails 项目中,我需要访问我的旧数据库。所以我创建了一些遗留模型。 我在照片和评论之间有一个多态关联(commentable_id 和 commentable_type)
当我打电话
Legacy::Photo.last.comments
它不起作用,因为 commentable_type 是“照片”而不是“LegcayPhoto”。
SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = $1 AND "comments"."commentable_type" = $2 [["commentable_id", 123], ["commentable_type", "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
遗产/comment.rb
module Legacy
class Comment < ActiveRecord::Base
establish_connection "legacy_#{Rails.env}"
#?? belongs_to :commentable, :polymorphic => true
end
end
我在 legacy/comments.rb 中也有问题。 有没有办法为 belongs_to 添加命名空间 :commentable, :polymorphic => true ?
最佳答案
也许不是最理想的方法,但您现在可以轻松地定义一个方法来返回一个 ActiveRecord 查询,该查询模仿 has_many
返回的内容,而不是构建 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)
它仍然有效。
关于ruby-on-rails - has_many 与多态关联中的 class_name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15269802/