这是我从旧数据库中移动数据的代码:
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'
。