Skip to content

Instantly share code, notes, and snippets.

@morgoth
Created February 24, 2014 10:02
Show Gist options
  • Save morgoth/9184921 to your computer and use it in GitHub Desktop.
Save morgoth/9184921 to your computer and use it in GitHub Desktop.
rails 4.1 cannot eager load polymorphic associations
gem 'activerecord', '4.1.0.rc1'
# gem 'activerecord', '4.0.2'
require 'active_record'
require 'minitest/autorun'
require 'logger'
puts ActiveRecord::VERSION::STRING
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
create_table :feed_entries, :force => true do |t|
t.integer :feedable_id
t.string :feedable_type
end
create_table :trainings, :force => true do |t|
t.integer :user_id
t.boolean :featured, default: false, null: false
end
create_table :users, :force => true do |t|
end
end
class FeedEntry < ActiveRecord::Base
belongs_to :feedable, polymorphic: true
def self.with_featured_training
joins("LEFT JOIN trainings ON feed_entries.feedable_type = 'Training' AND feed_entries.feedable_id = trainings.id")
.where(trainings: {featured: true})
end
end
class Training < ActiveRecord::Base
belongs_to :user
has_many :feed_entries, as: :feedable
end
class User < ActiveRecord::Base
end
class TestMe < MiniTest::Unit::TestCase
def test_polymorphic_eagerload
user_1 = User.create!
user_2 = User.create!
training_1 = Training.create!(user: user_1, featured: true)
training_2 = Training.create!(user: user_2, featured: true)
FeedEntry.create!(feedable: training_1)
FeedEntry.create!(feedable: training_2)
scope = FeedEntry.with_featured_training.includes(feedable: [:user])
scope.each { |fe| fe.feedable.user }
end
end
@morgoth
Copy link
Author

morgoth commented Feb 24, 2014

This throws error in rails 4.1, but it was working fine in 4.0.x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment