【问题标题】:has_many with class_name in polymorphic associationshas_many 与多态关联中的 class_name
【发布时间】:2013-03-07 11:19:20
【问题描述】:

在我的新 Rails 项目中,我需要访问旧数据库。所以我创建了一些遗留模型。 我在照片和 cmets 之间有一个多态关联(commentable_id 和 commentable_type)

当我打电话时

旧版::Photo.last.cmets

它不起作用,因为 commentable_type 是“Photo”而不是“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

我在 legacy/cmets.rb 中也有问题。 有没有办法为 belongs_to :commentable, :polymorphic => true 添加命名空间?

【问题讨论】:

  • 在Comment模型中,应该是belongs_to :photo, :class_name => Legacy::Photo
  • 但它不再是多态的。

标签: ruby-on-rails ruby-on-rails-3 rails-activerecord


【解决方案1】:

也许不是最理想的方法,但您现在可以轻松定义一个返回 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)

它仍然可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 2011-08-23
    • 2011-05-06
    相关资源
    最近更新 更多