ruby on rails, has_many, define class name for polymorphic relationship

class, has-many, polymorphism, ruby-on-rails

Solution

Recently I had similar problem, this is a solution that worked for me in 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

You have to add `unscope(:where)` to remove condition `uploaded_files.storage_type = 'Old::Recipe'` from query.

Problem

This is my code for moving data from my old database: ``` 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 ``` When I run the following code ``` Old::Recipe.all.each do |recipe| puts recipe.uploaded_files.to_sql end ``` It performs this SQL ``` SELECT `uploaded_files`.* FROM `uploaded_files` WHERE `uploaded_files`.`storage_id` = 38 AND `uploaded_files`.`storage_type` = 'Old::Recipe' ``` The problem is that I get: ``` `storage_type` = 'Old::Recipe' ``` But I need: ``` `storage_type` = 'Recipe' ``` How can I change the class for a polymorphic relationship? The doc for `has_many` doesn't give me an answer.

Original source