ruby-on-rails - has_many 与多态关联中的 class_name

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

在我的新 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/

相关文章:

ruby-on-rails - acts_as_list inside acts_as_tree

sql - 按属性将 Rails 查询分组到数组中

ruby-on-rails - JBuilder 模板永远不会被调用

ruby-on-rails - ruby on rails - 1 个错误禁止保存此列表 : Image has contents that are not what they are reported to be

ruby-on-rails - ActiveRecord 提取到 SQL

postgresql - Rails 和 ActiveRecord - 按纬度和经度划分的最近点

ruby-on-rails - NotImplementedError(仅支持部分劫持。)使用 message_bus

ruby-on-rails - 我是否需要手动为 HABTM 连接表创建迁移?

ruby-on-rails - 使用模型名称中的大写字母覆盖 Rails Controller 路由

ruby-on-rails - 来自浏览器的重复请求