ruby-on-rails - ruby on rails,has_many,定义多态关系的类名

标签 ruby-on-rails class polymorphism has-many

这是我从旧数据库中移动数据的代码:

class Old < ActiveRecord::Base
  establish_connection :old_version
  self.abstract_class = true

  class Recipe < self
    set_table_name :recipes
    has_many :uploaded_files, :as => :storage
  end

  class UploadedFile < self
    set_table_name :uploaded_files
    belongs_to :storage, :polymorphic => true
  end
end

当我运行以下代码时
Old::Recipe.all.each do |recipe|
  puts recipe.uploaded_files.to_sql
end

它执行此 SQL
SELECT `uploaded_files`.* FROM `uploaded_files`  WHERE `uploaded_files`.`storage_id` = 38 AND `uploaded_files`.`storage_type` = 'Old::Recipe'

问题是我得到:
`storage_type` = 'Old::Recipe'

但是我需要:
`storage_type` = 'Recipe'

如何更改多态关系的类?

has_many 的文档不给我答案。

最佳答案

最近我遇到了类似的问题,这是一个在 rails 4.2 中对我有用的解决方案:

class Recipe < self
  set_table_name :recipes
  has_many :old_files, -> (object) { unscope(where: :storage_type).where(storage_type: 'Recipe') }, class_name: 'UploadedFile'
end

您必须添加 unscope(:where)删除条件 uploaded_files.storage_type = 'Old::Recipe'从查询。

关于ruby-on-rails - ruby on rails,has_many,定义多态关系的类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10083667/

相关文章:

c++ - 定义整数之间的特殊除法

swift - Ios 开发 Swift 类和子类

java - 什么是运算符重载,它与多态性有什么不同?

ruby-on-rails - 如何拥有多个版本的 Ruby 和 Rails,以及它们在 Windows 上的组合?

php - 如何在 array_map 的可调用对象中实现类方法

c++ - 指向多态类层次结构中派生类型的智能指针,编译错误

c++ - 调用子类方法时出现段错误

ruby-on-rails - 数据库记录总是返回 'nil'

ruby-on-rails - Rails DateTime 对象不是我所期望的

ruby-on-rails - 如何在成功的ajax POST请求后渲染rails部分?