2012-04-10 39 views
5

Đây là mã của tôi cho việc di chuyển dữ liệu từ cơ sở dữ liệu cũ của tôi:Ruby on Rails, has_many, xác định tên lớp cho mối quan hệ đa hình

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 

Khi tôi chạy đoạn mã sau

Old::Recipe.all.each do |recipe| 
    puts recipe.uploaded_files.to_sql 
end 

Nó thực hiện này SQL

SELECT `uploaded_files`.* FROM `uploaded_files` WHERE `uploaded_files`.`storage_id` = 38 AND `uploaded_files`.`storage_type` = 'Old::Recipe' 

Vấn đề là tôi nhận được:

`storage_type` = 'Old::Recipe' 

Nhưng tôi cần:

`storage_type` = 'Recipe' 

Làm thế nào tôi có thể thay đổi lớp cho một mối quan hệ đa hình?

Tài liệu dành cho has_many không cho tôi câu trả lời.

+0

có lý do tại sao lớp Công thức được lồng trong lớp Cũ không? – pixeltrix

+0

Có lẽ điều này đã được chuyển vào một Rails Engine @pixeltrix. Bất cứ ai có một câu trả lời tốt hơn cho điều này? – Jwan622

Trả lời

0

Thật không may, bây giờ tôi thấy chỉ có một cách để làm điều đó:

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 

rất rất buồn

+0

Nhận xét trên không hoạt động? – Jwan622

1

Gần đây tôi đã có vấn đề tương tự, đây là một giải pháp mà làm việc cho tôi trong đường ray 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 

Bạn phải thêm unscope(:where) để xóa điều kiện uploaded_files.storage_type = 'Old::Recipe' khỏi truy vấn.

+0

có hoạt động không? – Jwan622

Các vấn đề liên quan