2012-04-10 15 views
5

これは私の古いデータベースからデータを移動するための私のコードです:ルビー、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のドキュメントは私に答えを与えません。

+0

なぜレシピクラスが古いクラスの中に入れ子になっているのでしょうか? – pixeltrix

+0

おそらく、これはRails Engine @pixeltrixに移されました。誰もがこれに対してより良い答えを持っていますか? – Jwan622

答えて

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 

非常に非常に悲しい

+0

上記のコメントは機能しませんでしたか? – Jwan622

1

最近、私は、これはレール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 

条件uploaded_files.storage_type = 'Old::Recipe'をクエリから削除するには、unscope(:where)を追加する必要があります。

+0

これは機能しますか? – Jwan622

関連する問題