5

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

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没有给我答案。

4

3 回答 3

9

最近我遇到了类似的问题,这是一个在 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'

于 2015-05-20T11:42:51.140 回答
3

上面 santuxus 的答案适用于 rails 4.2+

但是,对于较低版本,您可以尝试像这样覆盖关联:

class Recipe
  has_many :uploaded_files, conditions: { storage_type: 'Recipe' }, foreign_key: :storage_id
end
于 2019-03-26T10:00:43.433 回答
0

不幸的是,目前我只找到了一种方法:

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

  class Recipe < self
    set_table_name :recipes
    has_many :old_files,
             :class_name => 'UploadedFile',
             :finder_sql => Proc.new {
                %Q{
                  SELECT uploaded_files.*
                  FROM   uploaded_files
                  WHERE  uploaded_files.storage_id = #{id} AND
                         uploaded_files.storage_type = 'Recipe'
                }
              }
  end

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


namespace :old do
  task :menu => :environment do
    Old::Recipe.all.each do |recipe|
      puts '~' * 50
      puts recipe.id
      recipe.old_files.to_a.each do |file|
        puts file.storage_id, file.storage_type
      end
    end
  end
end

非常非常难过

于 2012-04-10T16:43:08.247 回答