Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 866
the-teacher Avatar asked Apr 10 '12 05:04

the-teacher


2 Answers

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.

like image 106
santuxus Avatar answered Nov 15 '22 03:11

santuxus


The answer by santuxus above is working properly for rails 4.2+

However, for lower versions, you could try overwriting the association like so:

class Recipe
  has_many :uploaded_files, conditions: { storage_type: 'Recipe' }, foreign_key: :storage_id
end
like image 41
Dāvis Namsons Avatar answered Nov 15 '22 05:11

Dāvis Namsons